Question

I'm trying to stub out a method on my current_user (using a modified restful_authentication auth solution) with rspec. I'm completely unsure of how I can access this method in my controller specs. current_user by itself doesn't work. Do I need to get the controller itself first? How do I do this?

Using rails 2.3.5, rspec 1.3.0 and rspec-rails 1.3.2

# my_controller_spec.rb
require 'spec_helper'

describe MyController do

  let(:foos){ # some array of foos }

  it "fetches foos of current user" do
    current_user.should_receive(:foos).and_return(foos)
    get :show
  end
end

Produces

NoMethodError in 'ChallengesController fetches foos of current user'
undefined method `current_user' for #<Spec::Rails::Example::ControllerExampleGroup::Subclass_1::Subclass_1::Subclass_2::Subclass_2:0x7194b2f4>
Was it helpful?

Solution

rspec-rails gives you a controller method for use in controller examples. So:

controller.stub!(:current_user).with(:foos).and_return(foos)

ought to work.

OTHER TIPS

how can it know where to find current_user? this should solve it:

subject.current_user.should_receive(:foos).and_return(foos)

I'm not entirely familiar with restful_authentication, just Authlogic and Devise, but it's probably similar in that current_user is a controller method and not an object, which is why calling should_receive on it isn't working as expected (you're setting an expectation on the object that current_user returns, but the method isn't accessible inside the scope of your expectation).

Try this:

stub!(:current_user).and_return(foos)

I read this and tweaked mine a bit. If you simply want to pass in a user object into your Rspec test, you can use this:

  1. First, create a user object within the rspec test. For example: (use whatever attributes you need or are required to create the user object.)

    user = User.create(name: "ted")

    (Note: you can also use a factory from FactoryGirl.)

  2. Now, with that user object which is saved into the variable "user", do this within that same Rspec test:

    controller.stub!(:current_user).and_return(user)

that should work...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top