Writing Model Tests for Enums
Basic Enum Test
Using RSpec, you can check if an enum is defined correctly:
RSpec.describe Order, type: :model do
it "has valid enum values" do
expect(Order.statuses.keys).to match_array(["pending", "confirmed", "shipped", "delivered", "canceled"])
end
end
This ensures that only expected statuses exist.
Testing Enum Methods
If your model has methods like confirm!
, you should test them:
RSpec.describe Order, type: :model do
let(:order) { Order.create(status: :pending) }
it "transitions correctly" do
order.confirm!
expect(order.status).to eq("confirmed")
end
it "does not allow invalid transitions" do
order.ship!
expect(order.status).not_to eq("shipped") # Should still be pending
end
end
This verifies that ship!
doesn’t work unless the order is confirmed first.
Testing Enum Callbacks
If an enum triggers notifications or background jobs, test them too:
RSpec.describe Order, type: :model do
let(:order) { Order.create(status: :pending) }
it "sends an email on confirmation" do
expect { order.confirm! }.to have_enqueued_mail(OrderMailer, :confirmation_email)
end
end
This ensures that emails are sent only when the status changes.