内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/7292061/testing-rest-api-responses-with-rspec-and-racktest
我有点闷了我有以下集成测试:
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总是似乎告诉我sign_in页面,即使我已经登录.
如果我删除Rack :: Test ::方法last_response消失,我可以使用响应,我得到当前的响应.一切似乎都行.
为什么是这样?响应方法来自哪里?可以使用响应来获取会话的上一个响应吗?
我需要使用last_response或类似的东西
last_response.headers["Location"].should eql(route)
所以我可以匹配路线.如果不是这样,我将被设置.
响应对于某些规格类型是自动的.
Rspec可能会混合ActionController :: TestCase :: Behavior for:type => :api块.
响应将来自ActionController :: TestCase :: Behavior,如下所示:type => :控制器块.
如果要在响应之前获得响应,请尝试将其存储在变量中,然后再进行下一个请求.
https://www.relishapp.com/rspec/rspec-rails/v/2-3/docs/controller-specs 和 https://github.com/rspec/rspec-rails 提供了一些有关各种规格类型混合的信息.
代码日志版权声明:
翻译自:http://stackoverflow.com/questions/7292061/testing-rest-api-responses-with-rspec-and-racktest
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Design for Hackers
David Kadavy / Wiley / 2011-10-18 / USD 39.99
Discover the techniques behind beautiful design?by deconstructing designs to understand them The term ?hacker? has been redefined to consist of anyone who has an insatiable curiosity as to how thin......一起来看看 《Design for Hackers》 这本书的介绍吧!