且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails/Rspec 使用 http 基本身份验证通过测试

更新时间:2022-06-25 20:40:02

更新 (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

信用这里