How to include a support file for rspec

Ricbermo picture Ricbermo · Dec 16, 2013 · Viewed 14k times · Source

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.

Answer

gotva picture gotva · Dec 16, 2013

I added this line in spec_helper.rb and it works in 3rd Rails

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

Maybe another (more pretty) solution exists