lost9123193
lost9123193

Reputation: 11030

Test a Nested Class Method in Rspec

Is there a way to test for the existence of a class method being called from another class method?

class AnimalRecord < ApplicationRecord
  COLLAR_ID = AnimalCollar::ID
  belongs_to :animal
  serialize :json, JSON
  scope :collar_id, -> { for_collar(COLLAR_ID) }

  def self.current_record(animal)
    animal_info = AnimalRecord.collar_id.first
    calculate_nutrients(animal_info)
  end

  def self.calculate_nutrients(animal)
    code result
  end
end

I can test the current_record method from current_record. But what is the proper way to test the calculate_nutrients method?

I had this:

context "test record" do
  before do
    @animal = create(:animal... )
    @animal_record = create(:animal_record...)
  end

  it "calls #calculate_nutrients" do 
    expected_response = responseHere
    expect(AnimalRecord).to receive(:calculate_nutrients).and_return(expected_response)

    AnimalRecord.current_record(@animal)
  end

But I get an error that says this:

    expected: 1 time with any arguments
       received: 0 times with any arguments

Upvotes: 0

Views: 377

Answers (1)

ka8725
ka8725

Reputation: 2918

I think you have do remove the line expect(AnimalRecord).to receive(:event) from the test example. Seems there is no such method defined on AnimalRecord, but you are trying to "expect" it.

Upvotes: 1

Related Questions