Reputation: 27603
When setting a default for a column in a migration, Rails picks this up just fine:
def change
add_column :account, :role, :string, default: 'mother'
Account.update_all(role: 'mother')
end
Accessing this in e.g. rails console works as expected:
Account.new.role #=> 'mother'
But, for some reason, not in rspec specs:
expect(Account.new.role).to equal 'mother' #fail
expect(Account.new.role).to not_be_nil #fail
I can imagine that rspec model specs try to avoid loading the schema and therefore know nothing about the default for an attribute. I am not sure if this is the reason though.
Is there some setting, magic trick or other call that will allow me to test the behaviour of such defaults.
Note: I am aware of the 'after_initialize' trick or even entire gems to set defaults, but this setting of a default in the migration seems the cleanest for me. Still, I'd like to test this.
Upvotes: 0
Views: 577
Reputation: 766
You can not keep symbols in the database. Rails automatically convert numbers & symbols in the string column by calling #to_s on them.
If you want to receive symbol for a database column then you should override the method in your model like this:
def role
read_attribute(:role).try(:to_sym)
end
Edit:
Have you run migrations for test environment? either RAILS_ENV=test rake db:schema:load or rake db:test:prepare. RSpec loads whole schema, otherwise you wouldn't be able to create any new instances of models using ActiveRecord
Upvotes: 1