diff --git a/README.md b/README.md index 5d5f292..9cf0de4 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ If you want to learn more about Form Objects you can check out [these great arti ### Why YAAF? -- It is [69 lines long](https://github.com/rootstrap/yaaf/blob/master/lib/yaaf/form.rb#L69). As you can imagine, we did no magic in such a few lines of code, we just leveraged Rails modules in order to provide our form objects with a Rails-like behavior. You can review the code, it's easy to understand. +- It is [71 lines long](https://github.com/rootstrap/yaaf/blob/master/lib/yaaf/form.rb#L71). As you can imagine, we did no magic in such a few lines of code, we just leveraged Rails modules in order to provide our form objects with a Rails-like behavior. You can review the code, it's easy to understand. - It provides a similar API to `ActiveModel` models so you can treat them interchangeably. diff --git a/lib/yaaf/form.rb b/lib/yaaf/form.rb index 18f2843..9cb7a3e 100644 --- a/lib/yaaf/form.rb +++ b/lib/yaaf/form.rb @@ -50,6 +50,8 @@ def save_in_transaction(options) end def save_models(options) + options.merge!(validate: false) + models.map { |model| model.save!(options) } end diff --git a/spec/support/models/user.rb b/spec/support/models/user.rb index 9702445..dbe94b7 100644 --- a/spec/support/models/user.rb +++ b/spec/support/models/user.rb @@ -1,3 +1,9 @@ class User < ActiveRecord::Base validates :name, presence: true + + validate :custom_validation + + def custom_validation + 'A validation method used in the specs' + end end diff --git a/spec/yaaf/model_validations_spec.rb b/spec/yaaf/model_validations_spec.rb new file mode 100644 index 0000000..24659fc --- /dev/null +++ b/spec/yaaf/model_validations_spec.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +RSpec.describe 'Model validations' do + let(:form) { WithValidationCallbacksForm.new(args) } + let(:email) { 'test@example.com' } + let(:name) { 'John' } + let(:args) do + { email: email, name: name, before_counter: 0, after_counter: 0 } + end + + context 'by default' do + let(:options) { {} } + + %i[save save!].each do |persistence_method| + it "calling #{persistence_method} runs the model validations only once" do + expect(form.user).to receive(:custom_validation).once + + form.send(persistence_method, options) + end + end + end + + context 'with validate: false' do + let(:options) { { validate: false } } + + %i[save save!].each do |persistence_method| + it "calling #{persistence_method} doesn't run model validations" do + expect(form.user).not_to receive(:custom_validation) + + form.send(persistence_method, options) + end + end + end +end