我整天都在和这个作斗争。Fabrication 或 FactoryGirl 的问题是一样的,所以我想这与 Active Record 或 Rails 有关。
让我们看下面的代码:
# app/models/category.rb
class Category < ActiveRecord::Base
before_validation :set_order
# Associations ------------------
belongs_to :company
# Validations -------------------
validates :name, :order, :presence => true
validates :order, :uniqueness => { :scope => :company, :message => "order should be unique" }
def set_order
return unless self.order.nil? || self.order.blank?
company_categories = self.template && self.company.categories.template || self.company.categories.non_template
self.order = (company_categories.empty? && 1) || (company_categories.map(&:order).sort.last + 1)
end
end
# spec/factories/companies.rb
Fabricator :company do
Fabricate.sequence(:name) { |n| "Company #{n}" }
creation_date Date.today
template false
end
# spec/factories/categories.rb
Fabricator :category do
name ["Business", "Finance", "Analytics"][Random.rand(3)]
template false
company
end
# spec/models/category_spec.rb
require 'spec_helper'
describe Category do
let(:category) { Fabricate(:category) }
it "has a valid factory" do
category.should be_valid
end
end
每次运行规范时,我都会收到以下错误:
1) Category has a valid factory
Failure/Error: let(:category) { Fabricate(:category) }
ActiveRecord::StatementInvalid:
PG::Error: ERROR: column categories.company does not exist
LINE 1: ..."categories" WHERE ("categories"."order" = 1 AND "categorie...
^
: SELECT 1 AS one FROM "categories" WHERE ("categories"."order" = 1 AND "categories"."company" IS NULL) LIMIT 1
# ./spec/models/category_spec.rb:4:in `block (2 levels) in <top (required)>'
# ./spec/models/category_spec.rb:7:in `block (2 levels) in <top (required)>'
看起来关联设置不正确。To sql 查询是“categories”.“company”而不是“categories”.“company_id”。这太奇怪了。
谢谢你的帮助!