【问题标题】:Rails 3.1, why I get ActiveRecord::UnknownAttributeError: unknown attribute in spec test?Rails 3.1,为什么我在规范测试中得到 ActiveRecord::UnknownAttributeError: unknown attribute?
【发布时间】:2012-01-04 05:57:28
【问题描述】:

我正在尝试在测试中创建Student 记录,如下所示:

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

但我收到此错误:

ActiveRecord::UnknownAttributeError: unknown attribute: work_phone

但是,work_phone 是在 Student 模型中定义的,并已迁移。

这是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

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord rspec2


    【解决方案1】:

    您是否仅在测试环境中收到此错误。更具体地说,当您使用

    运行测试时
    rake spec
    

    这可能是因为您没有在测试环境中运行迁移。 你可以这样做,

    rake db:migrate RAILS_ENV=test
    

    或在您的开发中运行迁移后,如下所示。

    rake db:migrate
    rake db:test:prepare 
    

    【讨论】:

    • 是的,这就是正确的原因,另外,我需要将 attr_accessor:work_phone 添加到模型中,谢谢
    • 使用rake db:test:prepare 准备测试数据库已为我解决了这个问题,谢谢。
    【解决方案2】:

    仅将 a​​ttr_accessor:work_phone 添加到模型也可以。

    【讨论】:

    • 我怀疑它起作用了,因为您现在在模型上有一个属性。但它可能只是将它保存在那个实例上。尝试重新加载模型,看看是否仍然可以在那里找到值。如果您打算确保它也被保存到数据库中,那么您将必须确保将记录保存到的数据库模式也具有相同的列。 (这意味着在这种情况下确保您已针对测试数据库运行迁移)。
    猜你喜欢
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 2013-02-20
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多