Posted about 5 years ago. Visible to the public.
Shoulda Matchers: how to test conditional validations
Shoulda Matchers
Archive
don't provide canditional validations (validations with if:
option). Here is how to write tests for the condition:
Class:
Copyclass Employee < ActiveRecored::Base validates :office, presence: true, if: manager? def manager? ... end end
Test:
Copydescribe Employee do describe '#office' do context 'is a manager' do before { allow(subject).to receive(:manager?).and_return(true) } it { is_expected.to validate_presence_of(:office) } end context 'is not a manager' do before { allow(subject).to receive(:manager?).and_return(false) } it { is_expected.not_to validate_presence_of(:office) } end end end
By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.