Rails 功能测试与必需的孩子
试图让这个功能测试通过:
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() 函数传递吗?
Trying to get this function test to pass:
test "should create question" do
assert_difference('Question.count') do
post :create, :question => @question.attributes
end
end
But @question has validators that require specific children to be present specifically one topic:
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
How would I 1) build the topic for @question in the test and then 2) pass it to the post method since it wouldnt be passed by the .attributes() function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
测试很好,需要更改的是控制器和/或模型。您尚未显示
create
操作的内容,但基本上有两种方法可以实现:或者,在
Question
中使用accepts_nested_attributes_for :topic
code> model,然后在 params 哈希中传递主题参数。哪种方法最好取决于您的具体情况。The test is fine, it's the controller and/or model that needs changing. You haven't shown the contents of the
create
action, but there are basically two ways to do it:Or, use
accepts_nested_attributes_for :topic
in theQuestion
model and then pass the topic parameters in the params hash. Which method is best depends on your specific circumstances.