【问题标题】:RSpecing :update action for a nested resourceRSpecing:更新嵌套资源的操作
【发布时间】:2023-05-26 14:42:01
【问题描述】:

作者有很多作品。作品归作者所有。

resources :authors do
  resources :works
end

还有 RSpec:

it "should redirect to :show" do
  work = FactoryGirl.create(:work)
  controller.stub(:resource) { work }
  work.should_receive(:update_attributes) { true }

  put :update, id: work.id, author_id: work.author.id, work: {}

  response.should redirect_to(admin_author_work_path(work.author, work))
end

还有错误:

Expected response to be a redirect to <http://test.host/admin/authors/353/works/166>
but was a redirect to <http://test.host/admin/authors/353/works>

为什么它不重定向到works_controller 的 :show 动作?我错过了什么吗?

我正在使用继承资源,因此使用的是 controller.stub(:resource)。
我还注意到 assign(:work, work) throws undefined method 'assign'?它适用于视图,难道它也适用于控制器吗?

【问题讨论】:

    标签: ruby-on-rails-3 bdd rspec2 inherited-resources


    【解决方案1】:

    这就是诀窍。

    it "should also redirect to :show" do
      author = mock_model(Author)
      work   = mock_model(Work)
    
      Author.stub(:find) { author }
      author.stub_chain(:works, :find) { work }
    
      work.should_receive(:update_attributes) { true }
    
      put :update, id: author.id, author_id: work.id, work: {}
    
      response.should redirect_to(admin_author_work_path(author, work))
    end
    

    所以看来我不能只使用 stub(:resource),看起来还需要其他东西。尝试使用 stub(:parent) 也没有运气。看来我不是很了解inherited_resources。

    欢迎评论。

    【讨论】:

      最近更新 更多