LoginSignup
6
1

More than 1 year has passed since last update.

Rails | shoulda-matchers で Boolean 型のバリデーションを検証できない

Last updated at Posted at 2017-02-24

問題

こんなモデルがあるとき

class Example < ActiveRecord::Base
  validates :Active, inclusion: { in: [ACTIVE_TYPES] }
end

Rspec で Boolean型のバリデーションを検証しようとすると

require 'rails_helper'

RSpec.describe Example, type: :model do
  it { is_expected.to validate_inclusion_of(:Active).in_array([true, false])  }
end

テストの削除をうながす警告が出る。

Warning from shoulda-matchers:

You are using `validate_inclusion_of` to assert that a boolean column
allows boolean values and disallows non-boolean ones. Be aware that it
is not possible to fully test this, as boolean columns will
automatically convert non-boolean values to boolean ones. Hence, you
should consider removing this test.

理由

「ActiveRecord が何でも Bloolean型にしてしまうので、結局ぜんぶテストが通るから意味ないよ」ってことっぽい?

Example.new(Active: 1)
# => #<Example:0x007f9f996fbe00 Active: true>

Example.new(Active: true)
# => #<Example:0x007f9f9b16f908 Active: true>

Example.new(Active: false)
# => #<Example:0x007f9f9cc92618 Active: false>

Example.new(Active: nil)
# => #<Example:0x007f9f9b1ce318 Active: nil>

Example.new(Active: 1)
# => #<Example:0x007f9f9cd7c9c0 Active: true>

Example.new(Active: 2)
# => #<Example:0x007f9f9daa34f0 Active: false>

Example.new(Active: 'TEXT')
# => #<Example:0x007f9f9cded3c8 Active: false>

環境

  • shoulda-matchers (3.1.1)
  • Rails 4.2.7.1

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

6
1
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
6
1