加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:31:35 所属栏目:百科 来源:网络整理
导读:我有点闷了我有以下集成测试: 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.c
我有点闷了我有以下集成测试:
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提供了一些有关各种规格类型混合的信息.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读