Rails / Rspec Maketesting通过http基本authentication

这里我的应用程序控制器文件(application_controller.rb)中的http基本身份validation

before_filter :authenticate protected def authenticate authenticate_or_request_with_http_basic do |username, password| username == "username" && password == "password" end end 

和我的家庭控制器的索引行动的默认testing(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 

由于validation方法,testing不会运行。 我可以评论“before_filter:authenticate”来运行它们,但我想知道是否有办法让它们与方法一起工作。

谢谢!

更新 :Matt Connolly提供了一个GIST,它也适用于请求和控制器规范: http : //gist.github.com/4158961


如果您有多个运行testing并且不希望每次都包含它(DRYer代码),则可以使用另一种方法:

创build一个/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 

在您的testing规格文件中:

 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 

在这里信用

对不起,我没有足够的,解决scheme似乎是以下几点:

 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 

当使用Rspec来testing葡萄API时,下面的语法工作

  post :create, {:entry => valid_attributes}, valid_session 

其中valid_session是

 {'HTTP_AUTHORIZATION' => credentials} 

 credentials = ActionController::HttpAuthentication::Token.encode_credentials("test_access1") 

一些答案build议设置request.env这是不安全的,因为请求可以nil ,你会最终与private method env' called for nil:NilClass ,尤其是当用rspec -e运行单个testing

正确的做法是:

 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 

这些是控制器和请求规格的绝佳解决scheme。

对于使用Capybara的功​​能testing,下面是一个解决scheme,使HTTP基本身份validation工作:

规格/支持/ 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 

那么,在你的规范中:

 feature 'User does something' do include_context 'When authenticated' # test examples end