2011-12-24 87 views
3

我有嵌套資源發生變化:在運行規格我asset_actions_controller_spec.rb測試嵌套資源控制器使用RSpec - 計數不通過1個

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 

resources :portfolios do 
    resources :asset_actions 
end 

而繼RSpec的控制器得到以下錯誤:

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

我可以'找出失敗的原因。有什麼建議麼?

注:的Rails 3.1.3,紅寶石1.9.3p5,RSpec的2.8.0

+0

同樣的問題發生時,測試銷燬行動 – dpaluy 2011-12-24 23:57:26

回答

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