2017-01-18 60 views
1
Devise: 4.20 
Rails: 5.0.1 
Rspec: 3.5 

我已經使用這個鏈接https://github.com/plataformatec/devise/wiki/How-To:-Use-HTTP-Basic-Authentication,但我havproblems測試HTTP基本身份驗證使用的請求RSpec的測試我的API。下面是示例性的錯誤:問題制定

應用程序/控制器/ API/base_controller.rb

module Api 
    class BaseController < ApplicationController 
    before_action :authenticate_user! 

    protected 

    def authenticate_user! 
     authenticate_or_request_with_http_basic do |username, password| 
     resource = User.find_by_username(username) 
     if resource 
      sign_in :user, resource if resource.valid_password?(password) 
     else 
      request_http_basic_authentication 
     end 
     end 
    end 
    end 
end 

應用程序/控制器/ API/V1/car_controller.rb

module Api 
    module V1 
    class CarController < Api::BaseController 
     respond_to :json 

     def index 
     @cars = Car.all 
     render :json => {:content => @cars}, :status => 200 
     end 
    end 
    end 
end 

規格/請求/ API /v1/car_controller_spec.rb

require 'rails_helper' 

RSpec.describe "Servers API", :type => :request do 
    it 'sends a list of servers' do 
    admin = FactoryGirl.create(:admin) 
    @env = {} 
    @env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(admin.username, admin.password) 
    get "/api/cars", :params => {}, :headers => @env 

    # test for the 200 status-code 
    expect(response.status).to eq(200) 

    end 
end 

當我運行規範,我有以下錯誤:

# --- Caused by: --- 
    # NoMethodError: 
    # undefined method `sign_in' for #<Api::V1::CarController:0x0000000609ef12> 
    # ./app/controllers/api/base_controller.rb:10 in block in authenticate_user! 

任何人都可以幫我嗎?謝謝。

回答

1

我有類似的設置,我的規格正在通過,你是否也會顯示你的spec_helper內容,看起來像你不包括Devise::TestHelpers

spec_helper

RSpec.configure do |config| 
    config.include Devise::TestHelpers 
    config.include Warden::Test::Helpers 
    config.before { Warden.test_mode! } 
    config.after { Warden.test_reset! } 

    config.before(:each) do 
    @headers = { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } 
    end 
end 

和我的測試看起來是這樣的:

RSpec.describe 'Users' do 
    context 'when client is authorized' do 
    let(:user) { FactoryGirl.create(:user) } 

    it 'gets user' do 
     @headers['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token. 
     encode_credentials(
      user.authentication_token, 
      email: user.email 
     ) 
     get api_v1_user_url(id: user.id), {}, @headers 
     expect(response.status).to eq(200) 
    end 
    end 
end