Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing REST-API responses with Rspec and Rack::Test

I am a bit stumped. I have the following integration test:

require "spec_helper"

describe "/foods", :type => :api do
  include Rack::Test::Methods

  let(:current_user) { create_user! }
  let(:host) { "http://www.example.com" }

  before do
    login(current_user)
    @food = FactoryGirl.create_list(:food, 10, :user => current_user)
  end

  context "viewing all foods owned by user" do

    it "as JSON" do
      get "/foods", :format => :json

      foods_json = current_user.foods.to_json
      last_response.body.should eql(foods_json)
      last_response.status.should eql(200)

      foods = JSON.parse(response.body)

      foods.any? do |f|
        f["food"]["user_id"] == current_user.id
      end.should be_true

      foods.any? do |f|
        f["food"]["user_id"] != current_user.id
      end.should be_false
    end

  end

  context "creating a food item" do

    it "returns successful JSON" do
      food_item = FactoryGirl.create(:food, :user => current_user)

      post "/foods.json", :food => food_item

      food = current_user.foods.find_by_id(food_item["id"])
      route = "#{host}/foods/#{food.id}"

      last_response.status.should eql(201)
      last_response.headers["Location"].should eql(route)
      last_response.body.should eql(food.to_json)
    end

  end

end

I've added the required Rack::Test::Methods to get me the last_response method but it doesn't seem to work right. last_response always seems to show me sign_in page even though I've already signed in.

If I remove Rack::Test::Methods last_response goes away and I can use response instead and I get the current response. Everything seems to works ok.

Why is this? Where is the response method coming from? Can I use response to get the previous response from the session?

I need to use the last_response, or something similar, for

last_response.headers["Location"].should eql(route)

so that I can match the routes. If it weren't for this I would be set.

like image 608
jdiaz Avatar asked Sep 03 '11 08:09

jdiaz


1 Answers

response is automatic for certain spec types.

Rspec probably mixes ActionController::TestCase::Behavior for :type => :api blocks.
response would come from ActionController::TestCase::Behavior, as it does for :type => :controller blocks.

If you want to get the response before that given by response, try storing it in a variable before you make the next request.

https://www.relishapp.com/rspec/rspec-rails/v/2-3/docs/controller-specs and https://github.com/rspec/rspec-rails give some information about what is mixed in with some of the various spec types.

like image 157
ronalchn Avatar answered Sep 17 '22 03:09

ronalchn