How to include a support file for rspec

Viewed 17488

I'm building a rails 4 app. I created a support file to simulate a login. Here are the files

spec/support/spec_test_helper.rb

module SpecTestHelper
  def login(user)
    request.session[:user_id] = user.id
  end

  def current_user
    User.find(request.session[:user_id])
  end
end

spec_helper.rb

config.include SpecTestHelper, :type => :controller

controller spec

describe BooksController, "user role" do

  user = Fabricate(:user) do
    role { Role.find_by_account_type("user") }
  end

  login(user)
end

The support file gives an undefined method error. This is part of the error message:

spec/controllers/books_controller_spec.rb:27:in `block in <top (required)>': undefined method `login' for #<Class:0x007f9f83193438> (NoMethodError)

I'm testing CanCan. I know the correct way to test CanCan is testing the Ability but that's already done.

5 Answers

in your spec only add such class or module like following

both files in the path: spec/

# frozen_string_literal: true

require "rails_helper"

class SharedHelper   
  def defined_action
    ...
  end
end

# frozen_string_literal: true

require "rails_helper"
require_relative "shared_helper"

RSpec.describe "Test request", type: :request do
  before(:all) do
    SharedHelper.new.defined_action
  end
end
Related