【问题标题】:Setting token and header in rspec test for JSON API在 JSON API 的 rspec 测试中设置令牌和标头
【发布时间】:2016-07-24 06:17:21
【问题描述】:

我正在尝试在 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

【问题讨论】:

  • 我们可以查看您的控制器代码及其用于验证请求的方法吗?

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


【解决方案1】:

事实证明,问题不在于我的代码,而在于我的测试数据库没有填充令牌。我为此有一个 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多