Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: Set enum field through FactoryGirl attributes

I have a Model that has an enum as attribute.

class ApplicationLetter < ActiveRecord::Base
  belongs_to :user
  belongs_to :event

  validates :user, :event, presence: true

  enum status: {accepted: 1, rejected: 0, pending: 2}

end

As well as a factory that generates this model and sets a value for the enum

FactoryGirl.define do
  factory :application_letter do
    motivation "motivation"
    user
    event
    status :accepted
  end
end

In a controller test I want to get valid attributes through the factory

let(:valid_attributes) { FactoryGirl.build(:application_letter).attributes }

and create a application with these attributes.

application = ApplicationLetter.create! valid_attributes

But I get the following error:

ArgumentError: '1' is not a valid status

Why is status interpreted as string? If I change the status in the factory I get the same error, but with the right corresponding number.

like image 627
Querenker Avatar asked Nov 27 '16 14:11

Querenker


2 Answers

you can do it more dynamically:

FactoryGirl.define do
  factory :application_letter do
    motivation "motivation"
    user
    event
    status { ApplicationLetter.statuses.values.sample }
  end
end

in this each time you will get different status

OR if wanna use static value you have to use integer, because enums by default use integer values

like image 173
Oleh Sobchuk Avatar answered Oct 06 '22 01:10

Oleh Sobchuk


All you need in your factory is status 'accepted'.

like image 37
Kees Briggs Avatar answered Oct 05 '22 23:10

Kees Briggs