【问题标题】:Include custom module in RSpec在 RSpec 中包含自定义模块
【发布时间】:2014-12-19 01:05:35
【问题描述】:

我从How-To:-Stub-authentication-in-controller-specs阅读教程

并尝试编写一些代码,但没有成功。有人可以帮我理解吗?谢谢

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

错误:

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

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    您应该在 it 块内编写测试:

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

    如果您想在任何测试之前执行此操作,您应该在 before 块内执行此操作:

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

    【讨论】:

    • 我想使用 'sign_in' 方法(如帮助方法)来存根登录用户,但 rspec 显示它未定义。
    • 它仍然失败并出现错误“未定义的局部变量或方法`sign_in'”
    • 您需要spec_helper 吗?你的代码是require 'rails_helper'
    • 我已经在 rails_helper 文件中有 require 'spec_helper' 行:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    相关资源
    最近更新 更多