Skip to content

Instantly share code, notes, and snippets.

@jcalvento
Last active May 24, 2018 18:42
Show Gist options
  • Save jcalvento/e557bc4fe56cae3794e2cb9052fb86b1 to your computer and use it in GitHub Desktop.
Save jcalvento/e557bc4fe56cae3794e2cb9052fb86b1 to your computer and use it in GitHub Desktop.

Shoulda matchers Provide one liner solutions for testing common functinoalities (like rails validations, AR relations and controller behaviors)

Example

Without matchers

it 'validates presence of name attribute' do
  subject.name = nil
  
  is_expected.to_not be_valid
  expect(user.errors.full_messages).to include "Name can't be blank"
end

Using matchers

it { is_expected.to validate_presence_of(:name) }

Real example - Amazon account model

it do
  is_expected.to validate_presence_of(:upload_limit)
  is_expected.to validate_numericality_of(:upload_limit).is_greater_than_or_equal_to(0)
  is_expected.to validate_presence_of(:delist_limit)
  is_expected.to validate_numericality_of(:delist_limit).is_greater_than_or_equal_to(0)
  is_expected.to validate_presence_of(:region)
  is_expected.to validate_inclusion_of(:region).in_array(described_class::REGIONS)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment