这里是应用程序控制器文件(application_controller.rb)中的http基本身份验证。
before_filter :authenticate
protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == "username" && password == "password"
end
end
和我的家庭控制器的索引操作的默认测试(spec/ controller / 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
由于身份验证方法的原因,测试无法运行。我可以注释"before_filter :authenticate“来运行它们,但我想知道是否有方法可以让它们与该方法一起工作。
谢谢!
发布于 2010-09-22 19:36:15
很抱歉,我没有找到足够的解决方案,解决方案似乎如下:
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
发布于 2016-12-23 03:56:24
一些答案建议设置request.env
,这是不安全的,因为请求可以是nil
,您将以private method env' called for nil:NilClass
结束,特别是在使用rspec -e
运行单个测试时
正确的方法是:
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
发布于 2014-06-19 14:14:04
使用Rspec测试Grape时,可以使用以下语法
post :create, {:entry => valid_attributes}, valid_session
valid_session在哪里
{'HTTP_AUTHORIZATION' => credentials}
和
credentials = ActionController::HttpAuthentication::Token.encode_credentials("test_access1")
https://stackoverflow.com/questions/3768718
复制相似问题