Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example specs for JSON Patch implementation in Rails model
# See: https://formapi.io/blog/posts/json-patch-with-rails-5-and-react/
require 'spec_helper'
describe Template do
describe 'applying JSON patches' do
let(:template) {
FactoryGirl.create(:template,
template_type: 'pdf',
fields: {
1 => {
x: 100,
},
2 => {
x: 100,
}
}
)
}
context "fields" do
it 'should apply a patch during update_attributes' do
template.update_attributes(
fields_patch: [{"op"=>"replace", "path"=>"/1/x", "value"=>150}]
)
expect(template.valid?).to eq true
expect(template.errors).to be_blank
expect(template.fields['1']['x']).to eq 150
end
it 'should add a validation error if the patch was not an array' do
template.update_attributes(
fields_patch: "/1/x"
)
expect(template.valid?).to eq false
expect(template.errors).to be_present
expect(template.errors[:fields].first).to include 'was not an array'
expect(template.fields['1']['x']).to eq 100
end
it 'should add a validation error if the patch cannot be applied' do
template.update_attributes(
fields_patch: [{"op"=>"replace", "path"=>"/missing/x", "value"=>150}]
)
expect(template.valid?).to eq false
expect(template.errors).to be_present
expect(template.errors[:fields].first).to include 'Could not apply JSON patch'
end
it 'should apply a patch manually' do
template.fields_patch = [{"op"=>"replace", "path"=>"/1/x", "value"=>false}]
expect(template.changed?).to eq true
expect(template.valid?).to eq true
expect(template.errors).to be_blank
expect(template.fields['1']['x']).to eq false
end
it 'should clear errors on reload' do
template.fields_patch = [{"op"=>"replace", "path"=>"/missing/x", "value"=>false}]
expect(template.valid?).to eq false
expect(template.errors[:fields]).to be_present
template.reload
expect(template.valid?).to eq true
expect(template.errors).to_not be_present
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment