Read more

Shoulda Matchers: how to test conditional validations

Daniel Straßner
June 26, 2017Software engineer at makandra GmbH

Shoulda Matchers Show archive.org snapshot don't provide canditional validations (validations with if: option). Here is how to write tests for the condition:

Class:

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

Test:

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

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot
Posted by Daniel Straßner to makandra dev (2017-06-26 11:54)