我有点难过。我有以下集成测试:
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::Methods 以获得 last_response
方法,但它似乎无法正常工作。 last_response
似乎总是显示登录页面,即使我已经登录。
如果我删除 Rack::Test::Methods last_response
消失,我可以使用 response
代替,我得到当前响应。一切似乎都正常。
这是为什么? response
方法来自哪里?我可以使用 response
从 session 中获取先前的响应吗?
我需要为
使用last_response
或类似的东西
last_response.headers["Location"].should eql(route)
这样我就可以匹配路线了。如果不是因为这个,我会被设置。
最佳答案
response
对于某些规范类型是自动的。
Rspec 可能为 :type => :api
block 混合了 ActionController::TestCase::Behavior
。
response
将来自 ActionController::TestCase::Behavior
,就像它对 :type => :controller
block 一样。
如果您想在 response
给出的响应之前获得响应,请尝试在发出下一个请求之前将其存储在变量中。
https://www.relishapp.com/rspec/rspec-rails/v/2-3/docs/controller-specs和 https://github.com/rspec/rspec-rails提供一些有关与某些不同规范类型混合的内容的信息。
关于ruby-on-rails - 使用 Rspec 和 Rack::Test 测试 REST-API 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7292061/