Reputation: 1305
I'm trying to define a test environment to make request programmatically to my Grape API.
I have the main API file into /app/api/services/v1.rb and i created a folder called requests into the spec path that have a file with this content for testing:
describe Services::V1 do
describe "GET /v1/users/:id" do
it "returns a user by id" do
user = User.create!
get "/api/users/#{user.id}"
expect(response.body).to eq user.to_json
end
end
end
The API have a path defined for the users resource but i have an error meaning that the Servicesnamespace is "uninitialized constant Services (NameError)"
I've added config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec/api/ into the spec_helper but i think that i'm misunderstanding the Grape doc related with that.
"You may want your API code to go into app/api - you can match that layout under spec by adding the following in spec/spec_helper.rb.
RSpec.configure do |config| config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec/api/ end"
Any help to make things work is appreciated. I'm a newbie with this technologies setup.
Upvotes: 2
Views: 2708
Reputation: 4558
If you add config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec/api/
in rails_helper.rb, it means you should put your api specs in /spec/api/
, not /spec/requests/
.
You should add require 'rails_helper'
in your /spec/api/services/v1/regious_spec.rb
Upvotes: 0
Reputation: 636
You need to test the resource not the api version.
describe "ExampleApi::V1::Regions" do
describe "GET /api/v1/regions/{id}" do
context "without data" do
it "should return a status code 404" do
get "/api/v1/regions/100000000", nil, { 'Authorization' => "Bearer #{token.token}"}
expect(response.status).to eq 404
end
it "should return an empty array" do
get "/api/v1/regions/100000000", nil, { 'Authorization' => "Bearer #{token.token}"}
expect(json['error']['code']).to eq(404)
end
end
context "with data" do
it 'returns a status code 200' do
get "/api/v1/regions", nil, { 'Authorization' => "Bearer #{token.token}"}
expect(response.status).to eq 200
end
it 'returns a region' do
region1 = Fabricate(:region)
get "/api/v1/regions/#{region1.id}", nil, { 'Authorization' => "Bearer #{token.token}"}
expect(json["id"]).to eq(region1.id)
end
end
end
end
On this example, the Authorization header is used in case you're using Authentication (on this case Oauth2).
There is also a helper or json, you can create a file on support folder:
module Requests
module JsonHelpers
def json
@json ||= JSON.parse(response.body)
end
end
end
on rails_helper.rb add:
# Just if the tests are in spec/api folder
config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec\/api/
Upvotes: 1