0

基本关联设置(注意,Customer 是 Person 模型的扩展):

Customer has_many :orders
Order belongs_to :customer

在 Customer.rb 中,我有以下类方法:

# SCOPE
def self.ordered_in_90_days
  joins(:orders).where('orders.created_at > ?', 90.days.ago)
end

在我的测试中,我有以下代码创建一个新订单(自动创建一个客户感谢 FactoryGirl),然后使用上面定义的 Customer 模型的 self 方法:

it "finds customers who have ordered within the last 90 days" do
  @order     = FactoryGirl.create(:order, created_at: 50.days.ago)
  @customer  = @order.customer

  Customer.count.should == 1  #passes
  Order.count.should == 1     #passes

  puts Customer.all.to_yaml   #for debugging, see below
  puts Order.all.to_yaml      #for debugging, see below

  Customer.ordered_in_90_days.should == [@customer]   #fails! returns: []
end

正在创建客户和订单,但在方法调用(空数组)中没有返回任何内容。我错过了什么?

以下是有关工厂的一些附加信息:

FactoryGirl.define do
    factory :customer do
        first_name "Wes"
        last_name "Foster"
        type "Customer"
    end

    factory :order do
        customer
    end
end

这是 Customer 和 Order 的调试输出(请记住,Customer 是 Person 的扩展,因此您看到的是 person_id 而不是 customer_id):

---
- !ruby/object:Customer
  attributes:
    id: 1
    first_name: Wes
    last_name: Foster
    type: Customer
    created_at: 2013-09-16 21:54:26.162851000 Z
    updated_at: 2013-09-16 21:54:26.162851000 Z
    middle_name: 
---
- !ruby/object:Order
  attributes:
    id: 1
    person_id: 
    created_at: 2013-07-28 21:54:26.135748000 Z
    updated_at: 2013-09-16 21:54:26.192877000 Z

(顾客

4

1 回答 1

1

调试输出确实表明了问题!查看订单检查:您的 person_id 为空白。

首先,即使 Customer 是 Person 的子类/扩展,Order 也会belongs_to :customer告诉 ActiveRecord 查找customer_id,而不是person_id。您是否指示应在 Order 模型上以非默认方式配置关联?

否则,我认为您可能错误地处理了 Order 工厂中的别名关联引用。我没有在我的项目中使用 factory_girl 关联别名引用——我试图将关联排除在我的工厂之外——但我会使用 factory_girl 文档验证您的方法:Association Aliases

我个人会在您的测试示例中尝试这个:

it "finds customers who have ordered within the last 90 days" do
  @customer  = FactoryGirl.create(:customer)
  @order     = FactoryGirl.create(:order, created_at: 50.days.ago, customer: @customer)

  Customer.count.should == 1  
  Order.count.should == 1     

  Customer.ordered_in_90_days.should == [@customer]
end

在示例中显式设置 @order.customer 可以消除工厂依赖性和复杂性。

旁注
如果您想在工厂中保留关联别名方法,并在其他测试中依赖该关联,我建议编写一个单独的测试来验证工厂关系是否正确实例化:

@order = create(:order)
expect(@order.customer).to be_a(Customer)

或类似的东西...

于 2013-09-16T22:13:00.740 回答