ruby-on-rails – 使用Rspec和Rack :: Test測試REST-API響應
我有點悶了我有以下整合測試:
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 => :控制器塊.
如果要在響應之前獲得響應,請嘗試將其儲存在變數中,然後再進行下一個請求.
ofollow,noindex" target="_blank">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