Skip to content

Instantly share code, notes, and snippets.

@kumaresan-rails
Last active June 14, 2021 04:10
Show Gist options
  • Save kumaresan-rails/7eb09cd633c093d4eb21dd8616c775bf to your computer and use it in GitHub Desktop.
Save kumaresan-rails/7eb09cd633c093d4eb21dd8616c775bf to your computer and use it in GitHub Desktop.
Graphiti - Polymorphic has many - Create
require 'rails_helper'
RSpec.describe "employees#create", type: :request do
subject(:make_request) do
jsonapi_post "/api/v1/employees", payload
end
describe 'basic create' do
let(:payload) do
{
data: {
type: 'employees',
attributes: {
# ... your attrs here
}
}
}
end
it 'works' do
expect(EmployeeResource).to receive(:build).and_call_original
expect {
make_request
}.to change { Employee.count }.by(1)
employee = Employee.last
expect(response.status).to eq(201)
end
end
describe 'complex create' do
let(:payload) do
{
data: {
"type": "employees",
"attributes": {
"first_name": "Shreya",
"last_name": "Ghoshal",
"age": 56
},
"relationships": {
"notes": {
"data": {
"temp-id": "abc123",
"type": "notes",
"method": "create"
}
}
}
},
"included": [
{
"temp-id": "abc123",
"type": "notes",
"attributes": {
"body": "Test Note",
}
}
]
}
end
it 'works' do
expect(EmployeeResource).to receive(:build).and_call_original
expect {
make_request
}.to change { Employee.count }.by(1)
employee = Employee.last
expect(employee.first_name).to eq('Shreya')
expect(employee.notes.count).to eq(1)
expect(employee.notes.first.body).to eq('Test Note')
expect(response.status).to eq(201)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment