[英]Rails/Rspec Make tests pass with http basic authentication
Here my http basic authentication in the application controller file (application_controller.rb)这是我在应用程序控制器文件 (application_controller.rb) 中的 http 基本身份验证
before_filter :authenticate
protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == "username" && password == "password"
end
end
and the default test for the index action of my home controller (spec/controllers/home_controller_spec.rb)以及我的家庭控制器的索引操作的默认测试(spec/controllers/home_controller_spec.rb)
require 'spec_helper'
describe HomeController do
describe "GET 'index'" do
it "should be successful" do
get 'index'
response.should be_success
end
end
Test doesn't run because of the authentication method.由于身份验证方法,测试未运行。 I could comment "before_filter :authenticate" to run them but I would like to know if there is way to make them worked with the method.我可以评论“before_filter :authenticate”来运行它们,但我想知道是否有办法让它们使用该方法。
Thank you!谢谢!
Update (2013): Matt Connolly has provided a GIST which also works for request and controller specs: http://gist.github.com/4158961更新(2013 年):Matt Connolly 提供了一个 GIST,它也适用于请求和控制器规范: http : //gist.github.com/4158961
Another way of doing this if you have many tests to run and don't want to include it everytime (DRYer code):如果您有许多测试要运行并且不想每次都包含它(DRYer 代码),另一种方法是:
Create a /spec/support/auth_helper.rb file:创建一个 /spec/support/auth_helper.rb 文件:
module AuthHelper
def http_login
user = 'username'
pw = 'password'
request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user,pw)
end
end
In your test spec file:在您的测试规范文件中:
describe HomeController do
render_views
# login to http basic auth
include AuthHelper
before(:each) do
http_login
end
describe "GET 'index'" do
it "should be successful" do
get 'index'
response.should be_success
end
end
end
Sorry I didn't seek enough, the solution seems to be the following:对不起,我没有寻求足够的,解决方案似乎如下:
describe "GET 'index'" do
it "should be successful" do
@request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")
get 'index'
response.should be_success
end
end
Some answers suggest to set request.env
which is unsafe, because request can be nil
and you will end up with private method env' called for nil:NilClass
, especially when run single tests with rspec -e
一些答案建议设置request.env
是不安全的,因为 request 可以是nil
并且你最终会得到private method env' called for nil:NilClass
,尤其是在使用rspec -e
运行单个测试时
Correct approach will be:正确的做法是:
def http_login
user = 'user'
password = 'passw'
{
HTTP_AUTHORIZATION: ActionController::HttpAuthentication::Basic.encode_credentials(user,password)
}
end
get 'index', nil, http_login
post 'index', {data: 'post-data'}, http_login
When using Rspec to test Grape APIs, the following syntax works使用 Rspec 测试 Grape API 时,以下语法有效
post :create, {:entry => valid_attributes}, valid_session
where valid_session is valid_session 在哪里
{'HTTP_AUTHORIZATION' => credentials}
and和
credentials = ActionController::HttpAuthentication::Token.encode_credentials("test_access1")
These are great solutions for controller and request specs.这些是控制器和请求规范的绝佳解决方案。
For feature tests using Capybara, here is a solution to make HTTP Basic authentication work:对于使用 Capybara 的功能测试,以下是使 HTTP 基本身份验证工作的解决方案:
spec/support/when_authenticated.rb规范/支持/when_authenticated.rb
RSpec.shared_context 'When authenticated' do
background do
authenticate
end
def authenticate
if page.driver.browser.respond_to?(:authorize)
# When headless
page.driver.browser.authorize(username, password)
else
# When javascript test
visit "http://#{username}:#{password}@#{host}:#{port}/"
end
end
def username
# Your value here. Replace with string or config location
Rails.application.secrets.http_auth_username
end
def password
# Your value here. Replace with string or config location
Rails.application.secrets.http_auth_password
end
def host
Capybara.current_session.server.host
end
def port
Capybara.current_session.server.port
end
end
Then, in your spec:然后,在您的规范中:
feature 'User does something' do
include_context 'When authenticated'
# test examples
end
My solution:我的解决方案:
stub_request(method, url).with(
headers: { 'Authorization' => /Basic */ }
).to_return(
status: status, body: 'stubbed response', headers: {}
)
Use gem webmock使用gem webmock
you can tighten verification by change:您可以通过更改来加强验证:
/Basic */ -> "Basic #{Base64.strict_encode64([user,pass].join(':')).chomp}"
URL - can be a regular expression URL - 可以是正则表达式
For me, with Rails 6, I need keyword arguments for rspec get method like .. get route, params: params, headers: headers
对我来说,使用 Rails 6,我需要 rspec get 方法的关键字参数,如 .. get route, params: params, headers: headers
Auth Helper method身份验证助手方法
module AuthHelper
def headers(options = {})
user = ENV['BASIC_AUTH_USER']
pw = ENV['BASIC_AUTH_PASSWORD']
{ HTTP_AUTHORIZATION: ActionController::HttpAuthentication::Basic.encode_credentials(user,pw) }
end
def auth_get(route, params = {})
get route, params: params, headers: headers
end
end
and the rspec request test.和rspec 请求测试。
describe HomeController, type: :request do
include AuthHelper
describe "GET 'index'" do
it "should be successful" do
auth_get 'index'
expect(response).to be_successful
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.