What is Shoulda-Matchers?
Shoulda-Matchers is a Ruby gem that makes testing model validations and associations easier with simple, one-line matchers. It helps keep model specs clear and maintainable by replacing longer, manual checks.
Why Use Shoulda-Matchers?
Installation & Setup
Gemfile
under the test
group:group :test do
gem 'shoulda-matchers', '~> 6.4'
end
bundle install
to install the gem.spec/rails_helper.rb
:Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
This makes sure that Shoulda-Matchers integrates seamlessly with RSpec and Rails.
Examples of Shoulda-Matchers in Model Specs
Shoulda-Matchers provides one-liners to test common validations and associations:
RSpec.describe Expense, type: :model do
it { should validate_presence_of(:name) }
it { should validate_presence_of(:amount) }
it { should validate_numericality_of(:amount).is_greater_than(0) }
it { should validate_presence_of(:date) }
end
belongs_to :user
):it { should. belong_to(:user) }
Other Examples:
it { should validate_numericality_of(:price).is_greater_than(0) }
it { should have_many(:expenses) }
Troubleshooting Common Issues
undefined method 'validate_presence_of'
rails_helper.rb
.type: :model
.