简体   繁体   English

在RSpec中包括自定义模块

[英]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 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 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 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 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: 您应该在it块中编写测试:

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: 如果要在任何测试之前执行此操作,则应在before块内执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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