views:

44

answers:

1

I have this controller code:

# GET /cardsets/1
def show
  @cardset = current_user.cardsets.find_by_id(params[:id])
end

And this RSpec test code (mocking with Mocha):

# GET Show
context "on get to show" do
  it "should assign cardset" do
    @cardset = Factory(:cardset)
    @profile = @cardset.profile

    @profile.cardsets.expects(:find).once.returns(@cardset)
    get :show, :id => @cardset.id
    assigns[:cardset].should_not be_nil
  end
end

This test fails with:

2)
Mocha::ExpectationError in 'CardsetsController for a logged in user on get to show should assign cardset'
not all expectations were satisfied
unsatisfied expectations:
- expected exactly once, not yet invoked: [#<Cardset:0x1032bb660>].find(any_parameters)
satisfied expectations:
- allowed any number of times, not yet invoked: ApplicationController.require_user(any_parameters)
- allowed any number of times, already invoked twice:     #<CardsetsController:0x10336c578>.current_user(any_parameters)

If I change the expectation to:

@profile.cardsets.expects(:find_by_id).once.returns(@cardset)

Then the test passes, why will this pass with find_by_id and not find?

+1  A: 

I think this is because find and find_by_id are actually different messages. Your controller uses find_by_id, but you are setting the message expectation to look for find.

zetetic
Cannot believe I wasnt seeing that. I am having another similar issue though. The #new action is setup the same as the #show action except it calls `current_user.cardsets.build` when using this `@profile.cardsets.expects(:build).returns(Factory.stub(:cardset))` to expect it, I get a failing test saying it has not been invoked.
trobrock