【问题标题】:Rails Functional Test With Required Children带有所需子项的 Rails 功能测试
【发布时间】:2011-02-06 17:28:02
【问题描述】:

试图让这个功能测试通过:

test "should create question" do
  assert_difference('Question.count') do
    post :create, :question => @question.attributes
  end
end

但是@question 的验证器要求特定的子节点出现在一个主题中:

  class Question < ActiveRecord::Base
    has_many :topic_questions
    has_many :topics, :through => :topic_questions

    validate :has_topic

    def has_topic
      (errors[:base] << "You must have one topic") if (topics.count < 1)
    end
  end

我将如何 1) 在测试中为 @question 构建主题,然后 2) 将其传递给 post 方法,因为 .attributes() 函数不会传递它?

【问题讨论】:

    标签: ruby-on-rails testing ruby-on-rails-3 functional-testing fixtures


    【解决方案1】:
    测试“应该创建问题”做 assert_difference('Question.count') 做 @question.topics"bla bla" ** 在这里设置你需要的属性} 发布 :create, :question => @question.attributes 结尾 结尾

    【讨论】:

    • 有没有办法使用以下方法做同样的事情? post :create, question: {topics: @a_topics_array}
    【解决方案2】:

    测试很好,需要更改的是控制器和/或模型。您还没有显示create 操作的内容,但基本上有两种方法可以做到:

    @question = Question.new(params[:question])
    @question.build_topic(<some_params>)
    if @question.save
      # ... etc ...
    

    或者,在Question 模型中使用accepts_nested_attributes_for :topic,然后在params 哈希中传递主题参数。哪种方法最好取决于您的具体情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多