Rails工厂协会失败

时间:2013-06-11 19:40:22

标签: ruby-on-rails rspec factory-bot rspec-rails fabrication-gem

我整天都在和这个人打架。问题与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)>'

看起来关联设置不正确。 sql查询是“类别”。“公司”而不是“类别”。“company_id”。这太奇怪了。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

它正在尝试按顺序运行验证。您的范围为company,而company代替company_id。尝试:

validates :order, :uniqueness => { :scope => :company_id }

答案 1 :(得分:0)

db尚未准备好。运行

rake db:migrate
rake db:test:prepare