Testing Rspec Rails 3.1集成测试。如何发送移动、http基本身份验证和JSON的post请求头?
我对Rails 3.1应用程序进行了RSPEC集成测试,该应用程序需要通过发出带有JSON参数的POST请求和需要使用http_基本身份验证的移动头来测试移动客户端的api 由于请求对象在集成测试中不可用,我有点卡住了 这是我目前掌握的代码Testing Rspec Rails 3.1集成测试。如何发送移动、http基本身份验证和JSON的post请求头?,testing,ruby-on-rails-3.1,rspec-rails,Testing,Ruby On Rails 3.1,Rspec Rails,我对Rails 3.1应用程序进行了RSPEC集成测试,该应用程序需要通过发出带有JSON参数的POST请求和需要使用http_基本身份验证的移动头来测试移动客户端的api 由于请求对象在集成测试中不可用,我有点卡住了 这是我目前掌握的代码 it "successfully posts scores" do # request.env["HTTP_ACCEPT"] = "application/json" #This causes an error as request is nly a
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的格式是否正确。谢谢你的帮助
get_basic_auth是一种帮助方法,如下所示
def get_basic_auth
user = 'user'
pw = 'secret'
ActionController::HttpAuthentication::Basic.encode_credentials user, pw
end
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
我在控制器中使用一个before_过滤器来检查移动和http_basic_身份验证,如下所示
def get_basic_auth
user = 'user'
pw = 'secret'
ActionController::HttpAuthentication::Basic.encode_credentials user, pw
end
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
我得到了一个重定向到登录,所以很明显,移动头是不被接受的,所以我真的不知道是否有任何其他头工作
更新
算出
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请求不需要“移动”用户代理
希望这能帮助别人