使用Rspec和Rack :: Test测试REST-API响应

jdi*_*iaz 15 ruby api integration-testing rspec ruby-on-rails

我有点难过.我有以下集成测试:

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

我已经添加了所需的Rack :: Test :: Methods来获取last_response方法,但它似乎无法正常工作.last_response即使我已经登录,似乎总是向我显示sign_in页面.

如果我删除Rack :: Test :: Methods last_response消失了,我可以使用response而且我得到当前的响应.一切似乎都运作正常.

为什么是这样?response方法来自哪里?我可以response用来从会话中获取先前的响应吗?

我需要使用last_response或类似的东西

last_response.headers["Location"].should eql(route)
Run Code Online (Sandbox Code Playgroud)

这样我就可以匹配路线了.如果不是为了这个我会被设定.

ron*_*chn 1

response对于某些规格类型是自动的。

Rspec 可能会混合ActionController::TestCase::Behavior用于:type => :api块。
response将来自ActionController::TestCase::Behavior,就像对于块一样:type => :controller

如果您想在 给出的响应之前获得响应response,请尝试在发出下一个请求之前将其存储在变量中。

https://www.relishapp.com/rspec/rspec-rails/v/2-3/docs/controller-specshttps://github.com/rspec/rspec-rails提供了有关混合内容的一些信息一些不同的规格类型。