Search code examples
ruby-on-railsrubyruby-on-rails-4rspecrspec-rails

Adding helper module to Rspec


I would like to add a module that includes a method to help me log in as a user. Here it is:

module TestHelper
  require 'spec_helper'

  ALL_USERS = ["administrator", "instructor", "regular_user"]

  def self.login_as(user_type)
    user = User.find_by(global_role_id: GlobalRole.send(user_type))
    @request.env["devise.mapping"] = Devise.mappings[:user]
    sign_in user
  end
end

The spec that's calling it is

require 'spec_helper'

RSpec.describe QuestionsController, :type => :controller do
  include Devise::TestHelpers
  include TestHelper

  describe "a test" do
    it "works!" do
      TestHelper.login_as("administrator")
    end
  end
end

And here is the spec_helper

RSpec.configure do |config|
  config.include TestHelper, :type => :controller

The error I get is: undefined method 'env' for nil:NilClass It looks like my module doesn't have access to @request.

My question is: how do I access and @request in the external Module?


Solution

  • You could pass @request in to TestHelper.login_as from the tests. Eg

    module TestHelper
      def self.login_as(user_type, request)
        ...
        request.env['devise.mapping'] = Devise.mappings[:user]
        ...
      end
    end
    
    ...
    
    describe 'log in' do
      it 'works!' do
        TestHelper.login_as('administrator', @request)
      end
    end
    

    But probably better to follow the macro pattern from the devise wiki if other devise mappings in play.