LoginSignup
0
0

More than 1 year has passed since last update.

【RSpec】shoulda-matchersを使ってテストを1行で書く

Last updated at Posted at 2021-10-29

環境

Ruby 3.0.2
Rails 6.1.4.1
shoulda-matchers 5.0.0

shoulda-matchersを使えばバリデーションテストが1行で書けるので大変便利

enumのテスト

model.rb
enum weather: { sunny: 0, cloudy: 1, rainy: 2 }
  • define_enum_for
spec.rb
describe 'enum' do
    it { is_expected.to define_enum_for(:weather).with_values(
      sunny: 0,
      cloudy: 1,
      rainy: 2
    ) }
end

バリデーションテスト

model.rb
validates :firstname, presence: true
validates :lastname, presence: true
validates :number, presence: true, uniqueness: true
validates :email, presence: true, uniqueness: true
  • validate_presence_of
  • validate_uniqueness_of
spec.rb
describe 'バリデーション' do
    it { is_expected.to validate_presence_of :firstname }
    it { is_expected.to validate_presence_of :lastname }
    it { is_expected.to validate_presence_of :number }
    it { is_expected.to validate_uniqueness_of :number }
    it { is_expected.to validate_presence_of :email }
    it { is_expected.to validate_uniqueness_of(:email).ignoring_case_sensitivity }
end

*ignoring_case_sensitivityについては過去記事参照

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0