简体   繁体   中英

Include custom module in RSpec

I read tutorial from How-To:-Stub-authentication-in-controller-specs

And try to write some code but it didn't work. Can anybody help me to understand? Thank you

spec/support/authen_helper.rb

module AuthenHelper
  def sign_in(user = double('user'))
    if user.nil?
      allow(request.env['warden']).to receive(:authenticate!).and_throw(:warden, {:scope => :user})
      allow(controller).to receive(:current_user).and_return(nil)
    else
      allow(request.env['warden']).to receive(:authenticate!).and_return(user)
      allow(controller).to receive(:current_user).and_return(user)
    end
  end

  def sign_in_as_admin(user = double('user'))
    allow(user).to receive(:role?).with('admin').and_return(true)
    allow(request.env['warden']).to receive(:authenticate!).and_return(user)
    allow(controller).to receive(:current_user).and_return(user)
  end
end

rails_helper.rb

ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
end

spec_helper.rb

require 'rubygems'

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'

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

RSpec.configure do |config|
  config.expect_with :rspec
  config.mock_with :rspec
  config.filter_run :focus
  config.run_all_when_everything_filtered = true
  config.order = :random
  config.color = true
  config.use_transactional_fixtures = false
  config.infer_spec_type_from_file_location!

  config.include AuthenHelper, :type => :controller
end

spec/controllers/api/v1/user_controller_spec.rb

require 'rails_helper'

module API
  module V1
    describe User, :type => :controller do
      sign_in
    end
  end
end

Error:

undefined local variable or method `sign_in' for RSpec::ExampleGroups::APIV1User:Class (NameError)

You should write the test inside an it block:

describe User, :type => :controller do
  it 'signs in' do
    sign_in
  end
end

If you want to do this before any test, you should do it inside a before block:

describe User, :type => :controller do
  before(:each) do
    sign_in
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM