-
-
Notifications
You must be signed in to change notification settings - Fork 909
Usage with validation_scopes
Dennis Dashkevich edited this page Nov 11, 2023
·
2 revisions
If you are using the excellent validation_scopes gem you'll find that it's not possible to use the shoulda matchers on the additional scopes.
This can be worked around with a bit of judicious monkey patching in a helper:
module ValidationScopesHelpers
def rewire_errors_to_warnings(object)
def object.valid?
has_warnings?
end
def object.errors
warnings
end
end
end
It's not the prettiest answer to this problem, but it does work! (extracted from here: https://github.com/thoughtbot/shoulda-matchers/issues/779#issuecomment-142329907)
Say we want to test the validation in this ActiveRecord object:
class Obj < ActiveRecord::Base
validates :name, presence: true
validation_scope :warnings do |o|
o.validates :address, presence: true
end
end
The test case would look like this:
include ValidationScopesHelpers
subject(:obj) { FactoryBot.build :obj }
context "regular validation tests" do
it { is_expected.to validate_presence_of(:name) }
end
context "validation warning tests" do
before { rewire_errors_to_warnings(obj) }
it { is_expected.to validate_presence_of(:address) }
end