ruby-on-rails – 使用Rspec和Rack :: Test测试REST-API响应

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 使用Rspec和Rack :: Test测试REST-API响应前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有点闷了我有以下集成测试:
  1. require "spec_helper"
  2.  
  3. describe "/foods",:type => :api do
  4. include Rack::Test::Methods
  5.  
  6. let(:current_user) { create_user! }
  7. let(:host) { "http://www.example.com" }
  8.  
  9. before do
  10. login(current_user)
  11. @food = FactoryGirl.create_list(:food,10,:user => current_user)
  12. end
  13.  
  14. context "viewing all foods owned by user" do
  15.  
  16. it "as JSON" do
  17. get "/foods",:format => :json
  18.  
  19. foods_json = current_user.foods.to_json
  20. last_response.body.should eql(foods_json)
  21. last_response.status.should eql(200)
  22.  
  23. foods = JSON.parse(response.body)
  24.  
  25. foods.any? do |f|
  26. f["food"]["user_id"] == current_user.id
  27. end.should be_true
  28.  
  29. foods.any? do |f|
  30. f["food"]["user_id"] != current_user.id
  31. end.should be_false
  32. end
  33.  
  34. end
  35.  
  36. context "creating a food item" do
  37.  
  38. it "returns successful JSON" do
  39. food_item = FactoryGirl.create(:food,:user => current_user)
  40.  
  41. post "/foods.json",:food => food_item
  42.  
  43. food = current_user.foods.find_by_id(food_item["id"])
  44. route = "#{host}/foods/#{food.id}"
  45.  
  46. last_response.status.should eql(201)
  47. last_response.headers["Location"].should eql(route)
  48. last_response.body.should eql(food.to_json)
  49. end
  50.  
  51. end
  52.  
  53. end

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

如果我删除Rack :: Test ::方法last_response消失,我可以使用响应,我得到当前的响应.一切似乎都行.

为什么是这样?响应方法来自哪里?可以使用响应来获取会话的上一个响应吗?

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

  1. 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-specshttps://github.com/rspec/rspec-rails提供了一些有关各种规格类型混合的信息.

猜你在找的Ruby相关文章