Rails/Rspec 使用 http 基本身份验证通过测试 [英] Rails/Rspec Make tests pass with http basic authentication
问题描述
这里是我在应用程序控制器文件 (application_controller.rb) 中的 http 基本身份验证
Here my http basic authentication in the application controller file (application_controller.rb)
before_filter :authenticate
protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == "username" && password == "password"
end
end
以及我的家庭控制器(spec/controllers/home_controller_spec.rb)的索引动作的默认测试
and the default test for the index action of my home controller (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
由于身份验证方法,测试未运行.我可以评论before_filter :authenticate"来运行它们,但我想知道是否有办法让它们使用该方法.
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.
谢谢!
推荐答案
更新 (2013):Matt Connolly 提供了一个 GIST,它也适用于请求和控制器规范:http://gist.github.com/4158961
Update (2013): Matt Connolly has provided a GIST which also works for request and controller specs: http://gist.github.com/4158961
如果您有许多测试要运行并且不想每次都包含它(DRYer 代码),另一种方法是:
Another way of doing this if you have many tests to run and don't want to include it everytime (DRYer code):
创建一个/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
在您的测试规范文件中:
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
信用这里
这篇关于Rails/Rspec 使用 http 基本身份验证通过测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!