2
votes

I am getting a uninitialized constant ControllerMacros (NameError), perhaps similar to these issues (1, 2, 3). I must be screwing up the syntax while trying to include controller macros so I can login with devise and pass controller tests in rspec. Link to GitHub repo. Rails 4.1.8 and Ruby 2.1.2

spec/controllers/static_pages_controller_spec.rb

require 'rails_helper'


describe StaticPagesController, :type => :controller do
  describe "GET #index" do
    it "responds successfully with an HTTP 200 status code" do
      login_user
      get :index
      expect(response).to be_success
      expect(response).to have_http_status(200)
    end

    it "renders the index template" do
      login_user
      get :root
      expect(response).to render_template("index")
    end
  end

end

spec/support/controller_macros.rb

module ControllerMacros
  def login_admin
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:admin]
      admin = FactoryGirl.create(:admin)
      sign_in :user, admin # sign_in(scope, resource)
    end
  end

  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      user = FactoryGirl.create(:user)
      user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
      sign_in user
    end
  end
end

added lines to spec/rails_helper

   #helps avoid authentication error during rspec:
    config.include Devise::TestHelpers, :type => :controller
    config.include ControllerMacros, :type => :controller
2

2 Answers

1
votes

I looks like you may need to add require 'support/controller_macros' to the top of your rails_helper.rb file. This directory would not be included by default with RSpec.

4
votes

This worked for me.

spec/support/devise.rb

require 'devise'

RSpec.configure do |config|
 config.include Devise::TestHelpers, :type => :controller
 config.extend ControllerMacros, :type => :controller
end

Also make sure this line is uncommented in rails_helper.rb

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