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)}