Following the instructions at https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-%28and-RSpec%29, I have set up some macros in a file spec/support/rspec_macros.rb
:
module ControllerMacros
def login_admin
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
sign_in FactoryGirl.create(:user, role: 4)
end
end
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
sign_in FactoryGirl.create(:user)
end
end
end
(Note that in my app, "admin" is a role -- role 4 -- that any user can be assigned to, and yes, once I get this working I'll DRY this up and get rid of the magic number).
However, putting login_admin
into my spec doesn't work: it can't see login_admin
.
So, following the advice at ControllerMacros cannot be seen in RSpec I add
config.include ControllerMacros, :type => :controller
to my spec_helper.rb
file. Now ControllerMacros
is an uninitialized constant, so following the advice at rspec not working with devise user authentication I add:
require 'support/controller_macros'
to my spec_helper
file, and I find that I'm back where I started with undefined local variable or method login_admin
Help! How do I get to the macro? And is there one single place where the whole process is documented?
For info, the relevant bits of my spec_helper
file are:
require 'rubygems' require 'factory_girl' require 'support/controller_macros'
require 'devise'
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
config.include ControllerMacros, :type => :controller
end
And my spec file is:
require 'rails_helper'
RSpec.describe UsersController, :type => :controller do
describe "GET show" do
login_admin
it "returns http success" do
user = User.first
get :show, id: user[:id]
expect(response).to be_success
end
end
end