我从How-To:-Stub-authentication-in-controller-specs
阅读教程尝试编写一些代码,但它不起作用。任何人都可以帮我理解吗?谢谢
规格/支持/ 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
规格/控制器/ 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)
答案 0 :(得分:0)
您应该在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