LoginSignup
0
0

More than 1 year has passed since last update.

【Rspec】バリデーションinclusionのテストはallow_valueを使おう

Posted at

Bookモデルに下記のバリデーションを定義し、
validate_inclusion_ofでバリデーションのテストをしようとするとテストが落ちる。

app/models/book.rb
class Book < ApplicationRecord
...
  validates :read, inclusion: { in: [true, false] } 
end
spec/models/book_spec.rb
it {is_expected.to validate_inclusion_of(:read).in_array([true, false])}

validate_inclusion_ofのソースにヒントがあった。

We discourage using `validate_inclusion_of` with boolean columns. In
fact, there is never a case where a boolean column will be anything but
true, false, or nil, as ActiveRecord will type-cast an incoming value to
one of these three values. That means there isn't any way we can refute
this logic in a test. Hence, this will produce a warning:

     it do
       should validate_inclusion_of(:imported).
       in_array([true, false])
     end

The only case where `validate_inclusion_of` *could* be appropriate is
for ensuring that a boolean column accepts nil, but we recommend
using `allow_value` instead, like this:

     it { should allow_value(nil).for(:imported) }

代替案の通りにテストを書くとグリーンになる!

spec/models/book_spec.rb
it {is_expected.to allow_value(true).for(:read)}
it {is_expected.to allow_value(false).for(:read)}
it {is_expected.not_to allow_value(nil).for(:read)}

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