在rspec中,user.invoices.count表示0,但它显示它有模型

时间:2013-04-14 01:31:18

标签: ruby-on-rails rspec

我正在构建用户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并且无法正常工作

1 个答案:

答案 0 :(得分:1)

这是因为发送.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