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

前端之家收集整理的这篇文章主要介绍了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
@H_403_4@我已经添加了所需的Rack :: Test :: Methods来获取last_response方法,但它似乎没有正常工作. last_response总是似乎告诉我sign_in页面,即使我已经登录.

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

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

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

last_response.headers["Location"].should eql(route)
@H_403_4@所以我可以匹配路线.如果不是这样,我将被设置.

解决方法

响应对于某些规格类型是自动的. @H_403_4@Rspec可能会混合ActionController :: TestCase :: Behavior for:type => :api块.
响应将来自ActionController :: TestCase :: Behavior,如下所示:type => :控制器块.

@H_403_4@如果要在响应之前获得响应,请尝试将其存储在变量中,然后再进行下一个请求.

@H_403_4@https://www.relishapp.com/rspec/rspec-rails/v/2-3/docs/controller-specshttps://github.com/rspec/rspec-rails提供了一些有关各种规格类型混合的信息.

原文链接:https://www.f2er.com/ruby/273583.html

猜你在找的Ruby相关文章