Rails 功能测试与必需的孩子

发布于 2024-10-16 03:33:50 字数 592 浏览 7 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

轮廓§ 2024-10-23 03:33:50
test "should create question" do
  assert_difference('Question.count') do
    @question.topics<<Topic.new(**set topics required and attribute here )
#or try this line of code 
    @question[:topics]={:name=>"bla bla" ** set attribute here what u need}
    post :create, :question => @question.attributes
  end
end
test "should create question" do
  assert_difference('Question.count') do
    @question.topics<<Topic.new(**set topics required and attribute here )
#or try this line of code 
    @question[:topics]={:name=>"bla bla" ** set attribute here what u need}
    post :create, :question => @question.attributes
  end
end
春花秋月 2024-10-23 03:33:50

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

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

或者,在 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:

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

Or, use accepts_nested_attributes_for :topic in the Question model and then pass the topic parameters in the params hash. Which method is best depends on your specific circumstances.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文