I'm trying to test a json written in rails in rspec. I'm not sure about the syntax. This is what I have so far:
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
I tried it in a bunch of different ways as you can see. But I'm getting a 403 error.
I'm using Rails 5.0.0.beta3
, ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]
and rspec-3.1
.
So it turns out, the problem was not with my code, but the fact that my test database was not populated with the token. I had a rake task for this and just running it with RAILS_ENV=test solved the issue. Also the code in my question is not very clean as I'm trying a bunch of different stuff to achieve the same result. Here's the final spec for anyone who might be interested:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.