3

I have nested resources:

resources :portfolios do
  resources :asset_actions
end

And following 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

While running Spec I got the following error:

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

I can't find the reason for this failure. Any suggestions?

Notes: Rails 3.1.3, Ruby 1.9.3p5, RSpec 2.8.0

dpaluy
  • 3,537
  • 1
  • 28
  • 42

1 Answers1

0

I think the problem is that @portfolio hasn't changed because it is a local variable. It's stored in memory and you've made changes to the database. So, you need to reload @portfolio to see it change. Try something like this:

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
user341493
  • 414
  • 1
  • 7
  • 15