matiasdim
matiasdim

Reputation: 527

Rspec - devise - rails: User session

I need to test the content of a view which has a devise authentication filter before_filter :authenticate_user!

When i run the test, the app doesn't have a logged user and redirects to /users/sign_in. Then the test searches the content on this view.

How can i simulate the user session or skip this filter to make the test, without using FactoryGirl ?

Thanks in advance

Upvotes: 2

Views: 782

Answers (2)

usha
usha

Reputation: 29349

Have a look at ControllerMacros

module ControllerMacros
   def login_user
    before(:each) do
      user = FactoryGirl.create(:user)
      @current_user = user
      sign_in user
    end
  end
end

spec/spec_helper.rb

RSpec.configure do |config|
  ....
  config.extend ControllerMacros, :type => :controller
end

spec/controllers/some_controller_spec.rb

require File.dirname(__FILE__) + '/../spec_helper'

describe SomeController, "index" do
    context "for authenticated users" do
        login_user
        ...
    end
end

It is pretty useful when you have controller logic based on different user roles.

Upvotes: 1

Josh
Josh

Reputation: 5721

Try adding this to your spec:

controller.class.skip_before_filter :authenticate_user!

An alternative(probably better) approach is to check out the devise docs to see their recommended testing pattern.

Upvotes: 1

Related Questions