问题描述
我有一个 Rails 3.1 应用程序的 RSPEC 集成测试,该应用程序需要通过发出带有 JSON 参数的 POST 请求和需要使用 http_basic 身份验证的移动标头来测试移动客户端的 api由于请求对象在集成测试中不可用,我有点卡住
I have an RSPEC integration test for a Rails 3.1 app that needs to test an api for a mobile client by issuing a POST request with JSON params and a mobile header that needs to use http_basic authenticationAs the request object is not available in an integration test I'm kinda stuck
这是我目前的代码
it "successfully posts scores" do
# request.env["HTTP_ACCEPT"] = "application/json" #This causes an error as request is nly available in controller tests
post "scores", :score => {:mobile_user_id => @mobile_user.id, :points => 50, :time_taken => 7275}.to_json,
:format => :json, :user_agent => 'Mobile', 'HTTP_AUTHORIZATION' => get_basic_auth
end
post 请求无法识别我使用的是 http 基本身份验证,但不确定 json 的格式是否正确.任何帮助表示赞赏
The post request does not recognise that I am using http basic authentication but unsure if the format for json is correct. Any help appreciated
get_basic_auth 是一个辅助方法,看起来像这样
get_basic_auth is a helper me4thod that looks like this
def get_basic_auth
user = 'user'
pw = 'secret'
ActionController::HttpAuthentication::Basic.encode_credentials user, pw
end
我在控制器中使用 before_filter 来检查移动设备和 http_basic_authentication 看起来像这样
I use a before_filter in my controllers that checks for mobile and http_basic_authentication that looks like this
def authorize
logger.debug("@@@@ Authorizing request #{request.inspect}")
if mobile_device?
authenticate_or_request_with_http_basic do |username, password|
username == Mobile::Application.config.mobile_login_name && Mobile::Application.config.mobile_password
end
else
unless current_user
redirect_to login_url, :notice => "Please log in"
end
end
end
我得到一个登录重定向,很明显移动头没有被接受,所以我真的不知道其他头是否有效
I get a redirect to login so obviously the mobile header is not being accepted so I have no idea really if any of the other headers are working
更新想通了
post("scores", {:score => {:mobile_user_id => @mobile_user.id, :points => 50, :time_taken => 7275}}.to_json,
{"HTTP_USER_AGENT" => "Mobile", 'HTTP_AUTHORIZATION' => get_basic_auth, 'HTTP_CONTENT_TYPE' => "application/json"})
这个技巧很好
推荐答案
我想出了我需要做什么
post("scores", {:score => {:mobile_user_id => @mobile_user.id, :points => 50, :time_taken => 7275}}.to_json,
{"HTTP_USER_AGENT" => "Mobile", 'HTTP_AUTHORIZATION' => get_basic_auth, 'HTTP_CONTENT_TYPE' => "application/json"}
显然不需要移动"用户代理来测试普通的 json 请求.
Obviously the "mobile" user agent is not needed to test normal json requests.
希望对某人有帮助
这篇关于Rspec Rails 3.1 集成测试.如何发送移动、http 基本身份验证和 JSON 的 post 请求标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!