1

我正在构建用户 rspec 测试。我有许多与用户关联的发票。在控制台中,当我执行 user.invoices 时,它会显示发票的哈希值。但是,当我执行 user.invoices.count 以获取该用户的发票数量时,它显示为 0。这是我的代码:

  before(:each) do
    @user = FactoryGirl.build(:user)

    @invoice = FactoryGirl.build(:invoice)
    @invoice.issue_date = "2013-01-01"
    @user.invoices << @invoice

然后如果我在那里放一个调试器,它会说 count = 0。这是输出:

(rdb:1) p user.invoices
[#<Invoice id: nil, user_id: 279, issue_date: "2013-01-01", due_date: nil, payment_term: "Net 15", discount: nil, created_at: nil, updated_at: nil, client_id: 140, client_invoice_id: 1, custom_message: nil, sent_to: nil, status: nil, public_id: "1234", grand_total: nil, user_name: nil, company_name: nil, custom_email_message: nil, address_line_one: nil, address_line_two: nil>, 
 #<Invoice id: nil, user_id: 281, issue_date: "2013-01-01", due_date: nil, payment_term: "Net 15", discount: nil, created_at: nil, updated_at: nil, client_id: 141, client_invoice_id: 1, custom_message: nil, sent_to: nil, status: nil, public_id: "1234", grand_total: nil, user_name: nil, company_name: nil, custom_email_message: nil, address_line_one: nil, address_line_two: nil>, 
 #<Invoice id: nil, user_id: 283, issue_date: "2012-01-01", due_date: nil, payment_term: "Net 15", discount: nil, created_at: nil, updated_at: nil, client_id: 142, client_invoice_id: 1, custom_message: nil, sent_to: nil, status: nil, public_id: "1234", grand_total: nil, user_name: nil, company_name: nil, custom_email_message: nil, address_line_one: nil, address_line_two: nil>, 
 #<Invoice id: nil, user_id: 285, issue_date: "2011-01-01", due_date: nil, payment_term: "Net 15", discount: nil, created_at: nil, updated_at: nil, client_id: 143, client_invoice_id: 1, custom_message: nil, sent_to: nil, status: nil, public_id: "1234", grand_total: nil, user_name: nil, company_name: nil, custom_email_message: nil, address_line_one: nil, address_line_two: nil>]
(rdb:1) p user.invoices.count
0

为什么计数不能正常工作?这是我试图通过的测试:

 it "should return the correct count of all invoices in the specified year" do
   # there are two invoices in 2013
   user = @user
   user.count_of_invoices_by_year("2013", :total).should == 2
 end

count_of_invoices_by_year 使用 .count 并且无法正常工作

4

1 回答 1

2

这是因为发送 .count 使用 COUNT(*) 查询数据库。由于您使用的是 FactoryGirl.build,因此数据库中没有记录,因此它返回 0。

另请参阅: http : //rhnh.net/2007/09/26/counting-activerecord-associations-count-size-or-length 其中解释了 .size、.length 和 .count 之间的区别。

编辑:这是测试您的方法的方法(这会将记录保存到数据库中,但在测试后它们将被销毁)

before(:each) do
  @user = FactoryGirl.create(:user)

  @invoice = FactoryGirl.create(:invoice)
  @invoice.issue_date = "2013-01-01"
  @invoice.save
  @user.invoices << @invoice
  @user.save
于 2013-04-14T03:02:53.300 回答