Recently, I get into problem while running controller spec. Iam using rspec with capybara and using devise gem for user authentication. While testing controller, I need to login a user. I tried to use Devise built in helper method
sign_out to manage user login logout, but it is not working at all. After, a lot of googling I find the solution at capybara wiki.
Devise’s built in
sign_out methods is not working because these require direct access to the request object which is not available while using Capybara. If, you are aware, Devise itself build over warden interface and warden do provide test helper to manage user login logout. So by, including warden test helper in controller spec, we can manage user login logout. The method provided by warden is: login_as and logout.
The sample code from one of my controller spec is as below
describe LoanDocumentsController do
@user = FactoryGirl.create(:user)
@user.terms_accepted_at = Time.now
@user.terms_declined_at = nil
describe “GET ‘index'” do
include Warden::Test::Helpers # this will include warden test helper and make login_as and logout method available to you
Warden.test_mode! # setting warden API to test mode
it “should load the index page if user logged in” do
page.should have_content(“Document Status”)
Since , we have authentication in all of our controller, instead of specifying warden configuration in all the controller spec, it is better to specify it once in spec_helper.rb file. As we can see, we are already requiring the spec_helper.rb. the configuration written in this file will be available to us. The spec_helper.rb with warden configuration will look like this
RSpec.configure do |config|