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

栏目: Ruby · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自: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-specshttps://github.com/rspec/rspec-rails 提供了一些有关各种规格类型混合的信息.

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/7292061/testing-rest-api-responses-with-rspec-and-racktest


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

大视觉创意宝典

大视觉创意宝典

2008-8 / 28.00元

《大视觉创意宝典:网页设计》主要内容:将优秀的网页分为设计、卡通、教育、金融、通讯、企业、房地产、娱乐等十四个章节,并详尽解析其页面布局、配色参考、设计特色及细节元素。丛书编写以设计基础的角度出发,具备速查、参照、案头工具书等功能。一起来看看 《大视觉创意宝典》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具