Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when checking enum value with shoulda-matchers

In my device model, I have

enum device_type: { ios: 1 , android: 2 }
validates :device_type, presence: true, inclusion: { in: device_types.keys }

And in my device_spec.rb, I write some tests for this like

describe 'validations' do
  subject { FactoryGirl.build(:device) }

  it { is_expected.to allow_values('ios', 'android').for(:device_type) }
  it { is_expected.to validate_inclusion_of(:device_type).in_array(%w(ios android)) }
  it { is_expected.not_to allow_value('windows').for(:device_type) }
end

When I ran rspec, the test allow_values('ios', 'android') was passed, but the remaining two were failed.

1) Device should ensure inclusion of device_type in ["ios", "android"]

Failure/Error: it { is_expected.to validate_inclusion_of(:device_type).in_array(%w(ios android)) }

 ArgumentError:
   '123456789' is not a valid device_type

2) Device should not allow device_type to be set to "windows"

Failure/Error: it { is_expected.not_to allow_value('windows').for(:device_type) }

 ArgumentError:
   'windows' is not a valid device_type

"It is not a valid device_type" is correct but why are these tests failed?

like image 848
Van Huy Avatar asked Dec 28 '15 15:12

Van Huy


1 Answers

When you define an attribute as enum, you can just test using Shoulda matchers

it { should define_enum_for(:device_type).with(:ios, :android) }

If you try to assign any other value, ActiveRecord will raise an ArgumentError (is not a valid device_type).

More recent shoulda syntax:

it { should define_enum_for(:device_type).with_values([:ios, :android]) }
like image 106
Ariel García Avatar answered Oct 19 '22 03:10

Ariel García