在rspec test中为JSON API设置标记和标头

时间:2016-04-04 15:45:09

标签: ruby-on-rails ruby json rspec json-api

我正在尝试在rspec中测试用rails写的json。我不确定语法。这就是我到目前为止所做的:

require 'rails_helper'

RSpec.describe V1::VersionsController, :type => :controller do

  before do
    @token = "0"
    request.env["Content-Type"] = 'application/vnd.api+json; charset=utf-8'
  end

  describe "GET index" do
    it "renders the index JSON" do
      @request.headers['Content-Type'] = 'application/vnd.api+json; charset=utf-8'
      request.env['Content-Type'] = 'application/vnd.api+json; charset=utf-8'
      params = { token: @token }
      get :index, :format => :json, token: @token
      #response.should be_success
      body = JSON.parse(response.body)
      ap body
    end
  end
end

我可以通过一系列不同的方式尝试它。但是我收到403错误。

我正在使用Rails 5.0.0.beta3ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]rspec-3.1

1 个答案:

答案 0 :(得分:0)

事实证明,问题不在于我的代码,而在于我的测试数据库没有填充令牌。我有一个rake任务,只是用RAILS_ENV = test运行它解决了这个问题。我的问题中的代码也不是很干净,因为我正在尝试一堆不同的东西来实现相同的结果。以下是可能感兴趣的任何人的最终规范:

require 'rails_helper'

RSpec.describe V1::VersionsController, :type => :controller do

  before do
    @token = "0"
    @request.headers['Content-Type'] = 'application/vnd.api+json; charset=utf-8'
  end

  describe "GET index" do
    it "renders the index JSON" do
      get :index, :format => :json, token: @token
      body = JSON.parse(response.body)
      expect(response.status).to eq 200
      expect(body["meta"]["app_name"]).to eq Rails.application.class.parent_name
      expect(body["meta"]["app_version"]).to eq ApplicationName.version
    end
  end

end