我有点困惑。我有以下集成测试:

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

我已经添加了所需的rack::test::方法来获取last_response方法,但它似乎不起作用。last_response尽管我已经登录,但似乎总是显示我登录页面。
如果删除rack::test::methodslast_response时,我可以使用response来代替它,并得到当前响应。一切似乎都正常。
这是为什么?response方法从何而来?我可以使用response从会话中获取先前的响应吗?
我需要使用last_response或类似的东西
last_response.headers["Location"].should eql(route)

这样我就能匹配路线。如果不是因为这个,我就完了。

最佳答案

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提供了一些与一些不同规格类型混合在一起的信息。

10-05 20:31
查看更多