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