Last active
February 8, 2020 22:37
-
-
Save rcoproc/62f2db9eb3481685432d964a7b8fc3ed to your computer and use it in GitHub Desktop.
Ruby JSON API with include_json and schema test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Json API Tests | |
# Para o código abaixo funcionar temos que configuras seguintes GEMS: | |
# gem 'rspec-json_expectations' # Utilizado no helper include_json | |
# gem 'json_matchers' # Utilizado pelo helper match_response_schema ... | |
require 'rails_helper' | |
RSpec.describe "Customers", type: :request do | |
describe "GET /customers" do | |
it 'JSON Schema' do | |
get '/customers/1.json' | |
expect(response).to match_response_schema("customer") | |
end | |
it "works! 200 OK" do | |
get customers_path | |
expect(response).to have_http_status(200) | |
end | |
it "index - JSON" do | |
get "/customers.json" | |
expect(response.body).to include_json([ | |
id: /\d/, | |
name: (be_kind_of String), | |
email: (be_kind_of String) | |
]) | |
end | |
it "show - JSON" do | |
get "/customers/1.json" | |
expect(response.body).to include_json( | |
id: /\d/, | |
name: (be_kind_of String), | |
email: (be_kind_of String) | |
) | |
end | |
it "show - Rspec puro + JSON" do | |
get "/customers/1.json" | |
response_body = JSON.parse(response.body) | |
expect(response_body.fetch("id")).to eq(1) | |
expect(response_body.fetch("name")).to be_kind_of(String) | |
expect(response_body.fetch("email")).to be_kind_of(String) | |
end | |
it 'create - JSON' do | |
member = create(:member) | |
login_as(member, scope: :member) | |
headers = { "ACCEPT" => "application/json"} | |
customers_params = attributes_for(:customer) | |
post "/customers.json", params: { customer: customers_params}, headers: headers | |
expect(response.body).to include_json( | |
id: /\d/, | |
name: customers_params[:name], | |
email: customers_params.fetch(:email) | |
) | |
end | |
it 'update - JSON' do | |
member = create(:member) | |
login_as(member, scope: :member) | |
headers = { "ACCEPT" => "application/json"} | |
customers = Customer.first | |
customers.name += " - ATUALIZADO" | |
patch "/customers/#{customers.id}.json", params: { customer: customers.attributes}, headers: headers | |
expect(response.body).to include_json( | |
id: /\d/, | |
name: customers.name, | |
email: customers.email | |
) | |
end | |
it 'destroy - JSON' do | |
member = create(:member) | |
login_as(member, scope: :member) | |
headers = { "ACCEPT" => "application/json"} | |
customers = Customer.first | |
expect{ delete "/customers/#{customers.id}.json", headers: headers }.to change(Customer, :count).by(-1) | |
expect(response).to have_http_status(204) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment