[rspec-users] how to stub the :current_user and any methods associated with it

David Chelimsky dchelimsky at gmail.com
Tue Apr 15 19:18:37 EDT 2008


On Apr 15, 2008, at 7:08 PM, newbie wrote:

>> Not sure why you are stubbing entries on the controller ... entries  
>> is
>> called on the current user ...
>
> I have this method. I want to use this variable to loop the users
> @entries. So I'm testing to see that this variable is tested and works
> correctly.
>
> def main
>    @entries = current_user.entries
> end
>
> I tried your suggestion
> @current_user = mock_model(User, :id => 1, :entries => [@entry])
>
> My error
> "Mock 'User_1010' received unexpected message :entries with (no args)"
>
> Maybe this is overtesting or not really necessary to test. Let me
> know.
>
> ----------------------------------
> I'm testing this out
> ----------------------------------
> def main
>    @entries = current_user.entries
> end
>
>
> ------------------------------------------
> Using this spec
> ------------------------------------------
>
> before(:each) do
>  @current_user = mock_model(User, :id => 1)
>  @entry = mock_model(Entry, :user_id => 1)
>  controller.stub!(:current_user).and_return(@current_user)
>  controller.stub!(:login_required).and_return(:true)
>  controller.stub!(:entries).and_return(@entry)
> end
>
> describe "on the main page" do
>  it "should show all the current entries for the user" do
>    @current_user = mock_model(User, :id => 1, :entries => [@entry])
>    get :main
>  end
> end

@current_user is being assigned values twice - once in before(:each)  
and once in describe "on the main page".

The mock that is raising the error is the one defined in  
before(:each), which is the one that is NOT told to expect :entries,  
and is the one that is returned by controller.current_user (per the  
3rd line of before(:each)).

That all make sense? Not really a mock or rspec problem but really  
just understanding how assignments work in Ruby.

HTH,
David


More information about the rspec-users mailing list