0

I'm trying to test the method cumulative_cost in my Product model.

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

So I'll run something like Product.where(name:"surfboard").cumulative_cost Let's say it returns two records, one with a cost of 1000, and another of 150, it'll return => 1150.

So here's what I've written as a test.

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

Then when I run my test, it fails.

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

Any help would be greatly appreciated.

thedanotto
  • 6,895
  • 5
  • 45
  • 43

2 Answers2

2

cumulative_cost is a class method on Product model. So, you have to call it like: Product.cumulative_cost.

The error is saying:

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

which means, you are calling this cumulative_cost method on an array but it's not implemented on array objects, hence it's getting this error.

Change your expectation to: (according to SteveTurczyn's answer)

expect(Product.where(name:"surfboard").cumulative_cost).to eq(1150)
K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
2

Following on from K M Rakbul Islam's answer...

products is an array because that's what Product.create! with a supplied array returns.

Your test should be...

expect(Product.where(name:"surfboard").cumulative_cost).to eq(1150)
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53