Search code examples
ruby-on-railsrubyrspecdeviserspec-rails

How to login in feature specs


I have a helper method that is using @request.env and Devise to login the user:

def login_user(user)
  @request.env["devise.mapping"] = Devise.mappings[:user]
  sign_in user
end

I'm trying to write a feature spec where I need to login, but login_user is failing:

1) Search finds a manufacturer
 Failure/Error: @request.env["devise.mapping"] = Devise.mappings[:user]

 NoMethodError:
   undefined method `env' for nil:NilClass
 # ./spec/support/controller_macros.rb:3:in `login_user'
 # ./spec/features/search_spec.rb:17:in `block (2 levels) in <top (required)>'

How can I fix? I have no experience with feature specs, with cucumber I'd use a feature to login, I'm definitely not sure that's the best practice with rspecs. Thanks in advance.


Solution

  • You can use Capybara as well to connect your test user. In my rails_helper I have this method:

    def create_user_and_log_in
      create :user, email: 'user@test.com', password: 'password'
      visit new_user_session_path
      fill_in :user_email, with: 'user@test.com'
      fill_in :user_password, with: 'password'
      click_on 'Connexion'
    end
    

    You can then call this method in your specs.