Reputation: 32355
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>
Upvotes: 6
Views: 3244
Reputation: 2200
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:
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.)
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...
Upvotes: 0
Reputation: 40900
how can it know where to find current_user
? this should solve it:
subject.current_user.should_receive(:foos).and_return(foos)
Upvotes: 1
Reputation: 47578
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.
Upvotes: 2
Reputation: 15562
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)
Upvotes: 0