Reputation: 360
So I was just trying to call a log_in method from user controller in the RSpec as
it "should get the index page" do
@user = User.new({ :email => "[email protected]" })
log_in(@user)
get 'index'
response.should be_success
end
The result I got is like
1) EmployeesController GET 'index' should get the index page
Failure/Error: log_in(user)
NoMethodError:
undefined method `log_in' for #<RSpec::Core::ExampleGroup::Nested_1:0x4ac0328>
# ./spec/controllers/employees_controller_spec.rb:11:in `user_log_in'
# ./spec/controllers/employees_controller_spec.rb:16:in `block (2 levels) in <top (required)>'
Can someone help me out? Thanks
Edited March 11th, 2011
Here is the log_in method which is in UserController
def log_in(user)
session[:current_user] = user.id
end
Upvotes: 2
Views: 11923
Reputation: 724
Why don't you stub logged_in? or whatever your method is. Logging in is not target of this spec, so stub it! Here's simple example how I spec controller action that has before_filter:
class MyController < ApplicationController
before_filter :logged_in?
def index
end
end
describe MyController do
describe "GET 'index'" do
context "when not logged in"
# you want to be sure that before_filter is executed
it "requires authentication" do
controller.expects :logged_in?
get 'index'
end
# you don't want to spec that it will redirect you to login_path
# because that spec belongs to #logged_in? method specs
end
context "when authenticated" do
before(:each) { controller.stubs :logged_in? }
it "renders :index template" do
get 'index'
should render_template(:index)
end
it "spec other things your action does when user is logged in"
end
end
end
Upvotes: 5
Reputation: 8412
If you want to call a method on the controller in an RSpec controller test, you could use the following.
subject.send(:log_in,@user)
It should call the method. I dont know if this is really a best practice. A better method would be to stub the logged_in method as BurmajaM suggested.
Upvotes: 14