Posted over 4 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:

Copy
class Employee < ActiveRecored::Base validates :office, presence: true, if: manager? def manager? ... end end

Test:

Copy
describe 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

Flaky tests are tests that sometimes fail for no obvious reason. They are the plague of many end-to-end (E2E) test suites that automate the browser through tools like Capybara and Selenium.

Join our free training event and learn to fix any flaky test suite, even in large legacy applications.

Owner of this card:

Avatar
Daniel Straßner
Last edit:
over 4 years ago
by Daniel Straßner
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Daniel Straßner to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more