Capybara 的 HTTP 基本身份验证
我正在为我的 Rails 3 应用程序编写一些 RSpec 测试,并尝试从 Webrat 切换到 水豚。到目前为止一切顺利,但应用程序使用 HTTP 基本身份验证来授权我的管理员用户,知道如何使用 Capybara 进行测试吗?
这是我当前的 Webrat 步骤:
it 'should authenticate for admin' do
basic_auth('user', 'secret')
visit '/admin'
response.status.should eql 200
response.status.should_not eql 401
end
如何使用 Capybara 执行此操作?谢谢!
I'm writing some RSpec tests for my Rails 3 application and trying to switch from Webrat to Capybara. So far so good but the application uses HTTP basic auth to authorize my admin user, any idea how I can test that with Capybara?
Here is my current Webrat step:
it 'should authenticate for admin' do
basic_auth('user', 'secret')
visit '/admin'
response.status.should eql 200
response.status.should_not eql 401
end
How do I do this with Capybara? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
让它工作
我使用
page.driver.basic_authorize(name,password)
代替更新:目前,在Capybara升级之后,我正在使用这堆解决方法:
I got it to work using
page.driver.basic_authorize(name, password)
insteadUpdate:
At the moment, after a Capybara upgrade, I'm using this pile of workarounds:
默认的 Capybara 驱动程序rack-test具有用于基本 HTTP 身份验证的
basic_authorize
方法(别名为authorize
),以及用于摘要 HTTP 身份验证的digest_authorize
,在这里你可以找到它们: https://github.com/brynary/rack -test/blob/master/lib/rack/test.rb所以你可以这样做:
或者你可以为基本 HTTP 身份验证编写一个简单的帮助程序:
The default Capybara driver, rack-test, has a
basic_authorize
method (with aliasauthorize
) for Basic HTTP Auth, anddigest_authorize
for Digest HTTP Auth, here you can find them: https://github.com/brynary/rack-test/blob/master/lib/rack/test.rbSo you can do:
Or you can write a simple helper for Basic HTTP Auth:
page.driver.*
解决方案都不适合我。我使用的是 Poltergeist,而不是 Selenium,所以这可能与此有关。这是有效的:然后,在您的规范中:
None of the
page.driver.*
solutions worked for me. I'm using Poltergeist, not Selenium, so that might have something to do with it. Here's what did work:Then, in your spec:
这在最近版本的 cucumber-rails 中发生了变化(我使用的是 1.0.2)。
cucumber-rails 默认使用 Rack/Test 驱动程序,因此如果您没有更改它,则以下说明将起作用。
创建 features/step_definitions/authorize.rb:
现在您可以在功能中使用它:
This has changed in recent versions of cucumber-rails (I am using 1.0.2).
cucumber-rails uses the Rack/Test driver by default, so if you have not changed that, the following instructions will work.
Create features/step_definitions/authorize.rb:
Now you can use this in your features:
我不得不做这个可怕的黑客让它工作值得无头和与JavaScript
I had to do this horrible hack to get it work worth headless and with javascript
伙计,这些解决方案都不适合我。
Pistos 的解决方案非常接近并适用于
js: true
的功能规范,但在无头时失败。下面的解决方案适用于两者无头和
js:true
规范。spec/support/when_authenticated.rb
然后,在您的规范中:
Man, none of these solutions worked for me.
Pistos' solution came close and worked for feature specs with
js: true
but failed when headless.This below solution works for me for both headless and
js: true
specs.spec/support/when_authenticated.rb
Then, in your spec: