2014-12-18 2 views
0

я прочитал учебник от How-To:-Stub-authentication-in-controller-specsВключить пользовательский модуль в RSpec

И попытаться написать код, но он не работал. Может ли кто-нибудь помочь мне понять? Спасибо

спецификации/поддержка/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

Вы должны написать тест внутри 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 
+0

Я хочу использовать метод 'sign_in', как вспомогательный метод, чтобы заглушить знак пользователя, но rspec показывает, что i t не определено. – PhuongTT

+0

@PhuongTT - см. Мое обновление –

+0

Он по-прежнему с ошибкой «неопределенная локальная переменная или метод' sign_in '" – PhuongTT

Смежные вопросы