我有嵌套资源:
resources :portfolios do
resources :asset_actions
end
关注RSpec Controller: 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
答案 0 :(得分:0)
我认为问题是@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