'Rails - How to test enum PostgreSQL data-type with rspec?

I'm using shoulda-matchers to test enum.

describe 'enum' do
  it do
    should define_enum_for(:gender).
    with([:male, :female, :others])
  end
end

Recently, I changed the column at the DB to enum data-type, as showed here

My current enum definition at the user model.

  enum gender: {male:'male', female:'female', others:'others'}

After that, my test fails (obviously) and shows the follow message.

 1) User enum should define :gender as an enum with [:male, :female, :others] and store the value in a column with an integer type

How can I test that with rspec?



Solution 1:[1]

Posting since I recently encountered the same issue.

You can specify the column type and values explicitly in RSpec:

it "defines an enum" do
  expect(field).to define_enum_for(:column_name)
                     .backed_by_column_of_type(:enum)
                     .with_values(male: "male", female: "female", others: "others")
end

Note:

  • :enum column type if you have a corresponding postgres enum defined; otherwise you can also use :string here. For the :enum type, RSpec expect the value :enum rather than the name of the enum.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt Redmond