使用shoulda宏进行测试失败并出现错误

时间:2010-06-19 15:57:30

标签: ruby-on-rails shoulda

我有模特:

class Company < ActiveRecord::Base
  attr_accessible :name, :address, :description, :email, :www   
  validates_presence_of :name, :address, :email
  validates_uniqueness_of :user, :name, :email
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
  has_many :items, :dependent => :destroy
  has_one :user  
end

测试用例:

class CompanyTest < ActiveSupport::TestCase
  should_allow_mass_assignment_of :name, :address, :description, :email, :www
  should_have_one :user
  should_have_many :items, :dependent => :destroy
  should_validate_uniqueness_of :name, :email  #failed
  should_validate_presence_of :name, :address, :email  #failed
  should_not_allow_values_for :email, "not valid email"  #failed
  should_allow_values_for :email, "test@test.com"  #failed
end

某些生成的测试失败并出现奇怪的错误:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: companies.user: SELECT "companies".id FROM "companies" WHERE ("companies"."user" IS NULL)  LIMIT 1

我无法理解为什么它试图访问公司表的“用户”列。它不存在,因为用户模型包含“belongs_to:company”和列“company_id”

2 个答案:

答案 0 :(得分:0)

Afaik has_one希望源表定义relation_id列。在您的情况下,我假设公司表存储user_id列。因此,您已更改has_one定义以指定方向和外键,或将其更改为belongs_to。

答案 1 :(得分:0)

验证不正确:

validates_uniqueness_of :user

没有这一行,一切都好!