ruby-on-rails 枚举类型的枚举列的Rspec

w8rqjzmb  于 2023-03-13  发布在  Ruby
关注(0)|答案(1)|浏览(199)

我有一个表作物,有一个enum字段crop_type,字段类型是PostGRES中的枚举字段,迁移如下:

def up
    create_table :crops do |t|
      t.string :name
      execute <<-SQL
      CREATE TYPE crop_type AS ENUM ('fruit', 'vegetable', 'other_crop');
      SQL
      t.column :crop_type, :crop_type
      t.timestamps
    end
  end

相关模型如下:

class Crop < ApplicationRecord
  enum crop_type: { fruit: 'fruit', vegetable: 'vegetable', other_crop: 'other_crop' }
end

现在,在我的模型规范中,我有下面一行:

it {
    should define_enum_for(:crop_type).with_values({ fruit: 'fruit', vegetable: 'vegetable', other_crop: 'other_crop' })
  }

但是,运行此测试会出现错误:

Expected Crop to define :crop_type as an enum backed by an integer,
       mapping ‹"fruit"› to ‹"fruit"›, ‹"vegetable"› to ‹"vegetable"›, and
       ‹"other_crop"› to ‹"other_crop"›. However, :crop_type is an enum column.

那么如何测试一个枚举字段,当它的类型是enum而不是Rails中的int时?

7tofc5zh

7tofc5zh1#

当Assert由枚举而不是整数支持的枚举时,请使用backed_by_column_of_type:

it {
  should define_enum_for(:crop_type)
    .with_values({ fruit: 'fruit', vegetable: 'vegetable', other_crop: 'other_crop' })
    .backed_by_column_of_type(:enum)
}

相关问题