【问题标题】:Testing Nested Resources Controller with RSpec - count doesn't change by 1使用 RSpec 测试嵌套资源控制器 - 计数不会改变 1
【发布时间】:2011-12-24 23:54:53
【问题描述】:

我有嵌套资源:

resources :portfolios do
  resources :asset_actions
end

并遵循 RSpec 控制器:asset_actions_controller_spec.rb

before(:each) do
  @portfolio = Factory(:portfolio)
end

describe "POST create" do
  describe "with valid params" do
    it "creates a new AssetAction" do
      expect {
        post :create, :asset_action => valid_attributes, :portfolio_id => @portfolio.id
        #@portfolio.asset_actions.create! valid_attributes #WORKS correctly, but this is Model
      }.to change(@portfolio.asset_actions, :count).by(1)
    end
  end
end

运行 Spec 时出现以下错误:

Failure/Error: expect {
   count should have been changed by 1, but was changed by 0

我找不到这次失败的原因。有什么建议吗?

注意事项:Rails 3.1.3、Ruby 1.9.3p5、RSpec 2.8.0

【问题讨论】:

  • 在测试 Destroy 动作时出现同样的问题

标签: ruby-on-rails-3 rspec2 nested-resources


【解决方案1】:

我认为问题在于@portfolio 没有改变,因为它是一个局部变量。它存储在内存中,并且您已对数据库进行了更改。因此,您需要重新加载 @portfolio 才能看到它的变化。试试这样的:

describe "POST create" do
  describe "with valid params" do
    it "creates a new AssetAction" do
      post :create, :asset_action => valid_attributes, :portfolio_id => @portfolio.id

      expect { @portfolio.reload }.to change(@portfolio.asset_actions, :count).by(1)
    end
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    相关资源
    最近更新 更多