Rspec Rails 3.1 Integration test. How to send post request headers for mobile, http basic authentication and JSON?

jamesc picture jamesc · Nov 4, 2011 · Viewed 7k times · Source

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 authentication As the request object is not available in an integration test I'm kinda stuck

This is the code I have so far

    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

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 is a helper me4thod that looks like this

  def get_basic_auth
    user = 'user'
    pw = 'secret'
    ActionController::HttpAuthentication::Basic.encode_credentials user, pw
  end

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

UPDATE Figured it out

  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"})

Does the trick nicely

Answer

jamesc picture jamesc · Aug 26, 2013

I figured out what I needed to do

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"}

Obviously the "mobile" user agent is not needed to test normal json requests.

Hope that helps someone