2

I just lately update my model with attr_accessible fields and suddenly some tests would not work, as i would expect. However, i have a spec like:

context "when user buys a game item" do
  let(:inventory) {@user.inventory << Factory(:inventory)}

  it "should present an error if the id ..." do
    GameItem.stub(:find_by_id).and_return(Factory(:game_item))
    @user.inventory.should == 1  # TEST
    post :buy, :id => (game_item.id + 1)
    flash[:error].should == I18n.t('error.invalid_post')
    response.should redirect_to melee_url('Weapon')
  end
end

The line @user.inventory.should == 1 is just a check that i made now. The inventory is nil for some reason. Does this happen because of the << operation? I would guess that this is most probable, due to the inventory_id attribute of the User model.

I have to say that attr_accessible generally seems like a hack to me and i kinda don't like it, though i can see why it should be used. Do you think this is the case? If so, how can i stay clear of that check?

John Bachir
  • 22,495
  • 29
  • 154
  • 227
Spyros
  • 46,820
  • 25
  • 86
  • 129

1 Answers1

2

let is lazy; it won't call the block unless the variable you're defining is used, and I don't see you accessing inventory anywhere. You access @user.inventory, but that's not the same thing.

Either lose the let definition and just put it in your it block, or make sure you call it first before you make sure it did what it was supposed to.

Robert Speicher
  • 15,382
  • 6
  • 40
  • 45
  • yes, i actually fixed it, was a mixture of things going on, including @user.inventory. thanx :) – Spyros Apr 18 '11 at 00:31