Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1, why I get ActiveRecord::UnknownAttributeError: unknown attribute in spec test?

I am trying to create a Student record in a test, like this:

student= Student.create!(:work_phone => "1234567890")

but I get this error:

ActiveRecord::UnknownAttributeError: unknown attribute: work_phone

However, work_phone is defined in the Student model, and migrated.

Here is the Studentmodel:

class Student < ActiveRecord::Base

  validates_length_of :work_phone, :is => 10, :message => 'must be 10 digits, excluding special characters such as spaces and dashes. No extension or country code allowed.', :if => Proc.new{|o| !o.work_phone.blank?}

  attr_accessible:work_phone

end

Any idea?

like image 866
simo Avatar asked Jan 04 '12 05:01

simo


2 Answers

Are you getting this error only in your test environment. More specifically, when you run tests using

rake spec

This could be happening becase you have not run your migrations on your test environments. You can either do,

rake db:migrate RAILS_ENV=test

or after having having run migrations on your development like below.

rake db:migrate
rake db:test:prepare 
like image 197
jake Avatar answered Jun 22 '23 03:06

jake


Only adding attr_accessor:work_phone to model also works.

like image 29
Beena Shetty Avatar answered Jun 22 '23 03:06

Beena Shetty