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!
任何人都可以幫我嗎?謝謝。