我想测试 Rails 3.2.3 中内置的基本 http 身份验证机制。我曾尝试在 RSpec 和 Cucumber 中测试 http 身份验证,但在这两个工具中都有一个失败的步骤。在 Cucumber 中,我在运行我的功能时收到以下消息:
When I perform HTTP authentication as "admin" with "test" # features/step_definitions/web_steps.rb:1
undefined method `env' for nil:NilClass (NoMethodError)
./features/step_definitions/web_steps.rb:3:in `/^I perform HTTP authentication as "([^\"]*)" with "([^\"]*)"$/'
features/sign_in_http.feature:4:in `When I perform HTTP authentication as "admin" with "test"'
这是我的 ApplicationController 类:
class ApplicationController < ActionController::Base
protect_from_forgery
http_basic_authenticate_with :name => "admin", :password => "test"
end
Cucumber 中的步骤定义:
When /^I perform HTTP authentication as "([^\"]*)" with "([^\"]*)"$/ do |username, password|
@request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")
visit '/'
end
黄瓜的特点:
Feature: Signing in via http
Scenario: HTTP sign-in
When I perform HTTP authentication as "admin" with "test"
Then I should see "Welcome to the app."
在 RSpec 中,http 身份验证步骤似乎通过了,但我从后续步骤中得到消息,它无法在页面上找到预期的内容,因为“访问被拒绝”:
1) ApplicationController sign in via http should be successful
Failure/Error: page.should have_content("Welcome to the app.")
expected there to be content "Welcome to the app." in "HTTP Basic: Access denied.\n"
# ./spec/controllers/application_controller_spec.rb:12:in `block (3 levels) in <top (required)>'
这是我的相关规格:
require 'spec_helper'
describe ApplicationController do
describe "sign in via http" do
it "should be successful" do
@request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("admin:test")
visit '/'
response.should be_success
page.should have_content("Welcome to the app.")
end
end
end
我还尝试在黄瓜步骤中的 http 授权行之前访问根路径,但这给了我关于 @request 的NilClass的相同消息。使用定义的“admin:test”凭据通过浏览器登录没问题,我可以看到我的应用程序的根页面。
如果有任何建议,我将不胜感激。