在测试 Rails 控制器时,如何将嵌套资源与多个 post 值混合?

发布于 2024-08-17 16:29:57 字数 537 浏览 3 评论 0原文

我有一个名为“Post”的模型,它是一个名为“Project”的模型下的嵌套资源,我正在尝试测试控制器。该代码可以在我的浏览器中找到,但我无法让它在测试中工作。这是测试

context "on POST to :edit" do
  setup do
    post( :edit,
      :project_id => @project1.to_param, 
      :id => @post1.to_param, 
      :post => { :title => 'new title', :text => 'other text' } 
    )
  end
  should_assign_to :post
  should_assign_to :project
  should_respond_with :success

  should "update post values" do
    assert_equal 'other text', assigns['post'].text
  end

你知道我是如何搞砸的吗?

I have a model called "Post" which is a nested resource under a model called "Project" and I'm trying to test the controller. The code works find in my browser, but I can't get it to work in the test. Here's the test

context "on POST to :edit" do
  setup do
    post( :edit,
      :project_id => @project1.to_param, 
      :id => @post1.to_param, 
      :post => { :title => 'new title', :text => 'other text' } 
    )
  end
  should_assign_to :post
  should_assign_to :project
  should_respond_with :success

  should "update post values" do
    assert_equal 'other text', assigns['post'].text
  end

Any idea how I'm screwing this up?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

纵山崖 2024-08-24 16:29:57

这是因为我不理解 Rails 的 REST 架构 - 或者 - 后语法。我应该使用 PUT 而不是 POST,并且调用应该如下所示:

context "on PUT to :update" do
  setup do
    put :update, { 
      :project_id => @project1.to_param, 
      :id => @post1.to_param, 
      :post => { :title => 'new title', :text => 'other text' } 
    } 
  end

  should_assign_to :post
  should_assign_to :project
  should_respond_with :success

  should "update post values" do
    assert_equal 'new title', assigns['post'].title
    assert_equal 'other text', assigns['post'].text
  end
end

我一直使用错误的语法,因为由于某种原因它仍然正确处理我的嵌套 id。

This was the result of me not understanding Rails' REST architecture -or- the post syntax. I should have been using PUT instead of POST, and the call should have looked like this:

context "on PUT to :update" do
  setup do
    put :update, { 
      :project_id => @project1.to_param, 
      :id => @post1.to_param, 
      :post => { :title => 'new title', :text => 'other text' } 
    } 
  end

  should_assign_to :post
  should_assign_to :project
  should_respond_with :success

  should "update post values" do
    assert_equal 'new title', assigns['post'].title
    assert_equal 'other text', assigns['post'].text
  end
end

I had been using the wrong syntax because for some reason it was still handling my nested id's correctly.

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