Rspec Rails 3.1集成测试.如何发送移动,http基本身份验证和JSON的发布请求标头?

jam*_*esc 13 testing rspec-rails ruby-on-rails-3.1

我对Rails 3.1应用程序进行了RSPEC集成测试,该应用程序需要通过发出带有JSON参数的POST请求和需要使用http_basic身份验证的移动头来测试移动客户端的API,因为请求对象在集成测试中不可用我有点卡住了

这是我到目前为止的代码

    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
Run Code Online (Sandbox Code Playgroud)

发布请求无法识别我使用的是http基本身份验证,但不确定json的格式是否正确.任何帮助赞赏

get_basic_auth是一个帮助me4thod,看起来像这样

  def get_basic_auth
    user = 'user'
    pw = 'secret'
    ActionController::HttpAuthentication::Basic.encode_credentials user, pw
  end
Run Code Online (Sandbox Code Playgroud)

我在我的控制器中使用了before_filter来检查看起来像这样的移动和http_basic_authentication

  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
Run Code Online (Sandbox Code Playgroud)

我得到一个重定向登录,所以显然移动标题没有被接受所以我不知道其他任何标题是否正常工作

更新想 出来了

  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"})
Run Code Online (Sandbox Code Playgroud)

诀窍很好

jam*_*esc 8

我想出了我需要做什么

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"}
Run Code Online (Sandbox Code Playgroud)

显然,不需要"移动"用户代理来测试正常的json请求.

希望能帮助别人