Home > OS >  How to test if a model has a custom macro method that is called during execution in Rspec
How to test if a model has a custom macro method that is called during execution in Rspec

Time:06-30

In my model, I run the method redefine_associations! during execution:

# frozen_string_literal: true
class MyModule < AnotherModule
  redefine_associations!
end

class AnotherModule < ApplicationRecord
  def self.redefine_associations!
    belongs_to :user
  end

  redefine_associations!
end

How can I test that my model has redefine_associations!.

I tried the following which did not work:

# frozen_string_literal: true
RSpec.MyModule VisitDate do
  it { expect(subject).to have_received(:redefine_associations!) }
  it { should respond_to(:redefine_associations!) }
end

CodePudding user response:

Since this is a macro method, the easiest way to test this would be:

  let(:class_file_array) do
    File.readlines(Rails.root.join('app/models/my_module.rb'))
  end

  it 'calls redefine_associations!' do
    expect(class_file_array.include?("  redefine_associations!\n")).to be true
  end

CodePudding user response:

As i understand you want to check if that redefine_associations method defined for that model. Then you can do it like this:

it { expect(subject.methods.includes?(:redefine_associations!)).to eql(true) }

  • Related