使用shoulda-matchers检查枚举值时出错

问题描述 投票:8回答:1

在我的device模型中,我有

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

在我的device_spec.rb中,我为此写了一些测试

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

当我运行rspec时,测试allow_values('ios', 'android')通过,但其余两个都失败了。

1)设备应确保在[“ios”,“android”]中包含device_type

失败/错误:它{is_expected.to validate_inclusion_of(:device_type).in_array(%w(ios android))}

 ArgumentError:
   '123456789' is not a valid device_type

2)设备不应允许将device_type设置为“windows”

失败/错误:{is_expected.not_to allow_value('windows')。for(:device_type)}

 ArgumentError:
   'windows' is not a valid device_type

“它不是有效的device_type”是正确的,但为什么这些测试失败了?

ruby-on-rails rspec shoulda
1个回答
0
投票

将属性定义为枚举时,可以使用Shoulda匹配器进行测试

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

如果您尝试tu分配任何其他值,ActiveRecord将引发ArgumentError(不是有效的device_type)

© www.soinside.com 2019 - 2024. All rights reserved.