【问题标题】:Testing http basic authentication with Cucumber and Capybara使用 Cucumber 和 Capybara 测试 http 基本身份验证
【发布时间】:2011-11-21 11:50:19
【问题描述】:

我正在尝试使用 Cucumber 和 Capybara 测试 authenticate_or_request_with_http_basic 方法,但它不起作用。

有什么建议吗?

授权控制器:

before_filter :authorize

def show
 flash[:notice] = 'Welcome back!'
end  

private

def authorize
 authenticate_or_request_with_http_basic do |username, password|
  username == "admin" && password == "password"
 end
end

黄瓜功能:

Scenario: Successful login
  When I log in as "admin" with "password"
  Then I should see "Welcome back!"

黄瓜步:

When /^I log in as "([^\"]*)" with "([^\"]*)"$/ do |username, password|
  visit authorization_path
  authorize username, password
end

错误信息:

expected there to be content "Welcome back!" in "HTTP Basic: Access denied.\n" (RSpec::Expectations::ExpectationNotMetError)

我也尝试过使用以下命令,但它也不起作用:

page.driver.browser.basic_authorize(username, password)

【问题讨论】:

  • 你能澄清一下“不起作用”吗?您需要向我们解释如何它不起作用。您在什么时候收到什么错误消息?有堆栈跟踪吗?它在日志中说什么?等等
  • Taryn,页面给出了一个 HTTP 基本:访问被拒绝,因为用户无法被授权。我可以通过浏览器登录就好了。如果我通过浏览器跳过授权,我会收到与黄瓜显示的相同的错误消息。

标签: ruby-on-rails cucumber capybara


【解决方案1】:

使用 selenium 网络驱动程序并访问该网站 page.driver.visit("https://username:password@example.com")

【讨论】:

  • 好电话。请注意,如果您使用的是Capybara,那只是Selenium 和浏览器之间的数据服务层。如果Capybara 中的某些内容不起作用,则回退是直接来自Seleniumpage.driver 命令。
【解决方案2】:

好的,所以 - 信息在什么时候无法通过。尝试在适当的位置添加 log/puts 语句来探测这一点。

When /^I log in as "([^\"]*)" with "([^\"]*)"$/ do |username, password|
  puts "got into the test-helper with: #{username.inspect} and #{password.inspect}"
  visit authorization_path
  authorize username, password
end


def authorize
  puts "in the authorize method before actually trying to authorize"
  authenticate_or_request_with_http_basic do |username, password|
    puts "inside authorize, trying to authenticate against: #{username.inspect} and #{password.inspect}"
    username == "admin" && password == "password"
  end
end

如果您可以在日志/输出中看到其中任何一个,那么至少您会知道 uername/password 在代码中达到了这一点

【讨论】:

  • Taryn,我正在比较控制器内部的字符串(用户名 == "admin" && 密码 == "password")。该站点将只有一个用户/管理员。基于 Http 的授权不需要表。
  • 啊,是的,抱歉我没注意到。 :P
  • 尝试一些 put 探测(请参阅更新的答案)至少让我们知道我们在什么时候未能获得正确的信息
  • Taryn,我可以看到前两个 put,但看不到最后一个(puts “inside authorize...”)。我发现了更多关于 SO 的主题提出了同样的问题,但没有找到解决方案。我决定放弃并建立一个基于 cookie 的身份验证,现在一切都在通过。非常感谢帮助我调试这个问题!
  • 这意味着问题更根本 - 即它甚至没有到达调用该代码的地步。所以是的 - 可能是改变策略的一个很好的呼吁 - 除非你真的想深入了解原因和原因。 :P
【解决方案3】:

我认为您正在另一个页面上显示欢迎消息。如果是这种情况,则缺少一个步骤。

Scenario: Successful login
  When I log in as "admin" with "password"
  Then I should be on some page
  Then I should see "Welcome back!"

【讨论】:

  • Mahesh,我来回改变控制器行为试图解决这个问题。我正在再次编辑问题,不包括重定向。问题是因为授权失败,无法重定向或者给闪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-04
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多