0

我正在尝试cumulative_cost在我的Product model.

#app/models/product.rb
class Product < ActiveRecord::Base
  class << self
    def cumulative_cost
      self.sum(:cost)
    end
  end
end

所以我会运行类似Product.where(name:"surfboard").cumulative_cost假设它返回两条记录,一条成本为 1000,另一条成本为 150,它将返回=> 1150

所以这就是我写的测试。

RSpec.describe Product, "class << self#cumulative_cost" do
  it "should return the total cost of a collection of products"
    products = Product.create!([{name:"surfboard", cost:1000}, {name:"surfboard", cost:150}])
    expect(products.cumulative_cost).to eq(1150)
  end
end

然后,当我运行测试时,它失败了。

undefined method `cumulative_cost' for #<Array:0x007fe3e31844e8>

任何帮助将不胜感激。

4

2 回答 2

2

cumulative_cost是模型上的类方法Product。所以,你必须这样称呼它:Product.cumulative_cost.

错误是说:

undefined method `cumulative_cost' for #<Array:0x007fe3e31844e8>

这意味着,您在数组上调用此cumulative_cost方法,但未在数组对象上实现,因此会出现此错误。

将您的期望更改为:(根据 SteveTurczyn 的回答)

expect(Product.where(name:"surfboard").cumulative_cost).to eq(1150)
于 2015-08-31T22:03:07.987 回答
2

继 KM Rakbul Islam 的回答之后......

products 是一个数组,因为这就是Product.create!提供的数组返回的结果。

你的测试应该是...

expect(Product.where(name:"surfboard").cumulative_cost).to eq(1150)
于 2015-08-31T22:08:12.677 回答