1

I have the following in my module:

module SimilarityMachine

...

  def answers_similarity(answer_1, answer_2)
    if answer_1.compilation_error? && answer_2.compilation_error?
      return compiler_output_similarity(answer_1, answer_2)
    elsif answer_1.compilation_error? || answer_2.compilation_error?
      return source_code_similarity(answer_1, answer_2)
    else
      content_sim = source_code_similarity(answer_1, answer_2)
      test_cases_sim = test_cases_output_similarity(answer_1, answer_2)
      answers_formula(content_sim, test_cases_sim)
    end
  end

...

end

I would like to test these "if conditions", to ensure that the right methods are called (all these methods are from SimilarityMachine module). To do that, I have:

describe SimilarityMachine do
  describe '#answers_similarity' do
    subject { answers_similarity(answer_1, answer_2) }
    let(:answer_1) { create(:answer, :invalid_content) }

    context "when both answers have compilation error" do
      let(:answer_2) { create(:answer, :invalid_content) }

      it "calls compiler_output_similarity method" do
        expect(described_class).to receive(:compiler_output_similarity)
        subject
      end
    end
end

With both answers created I go to the right if (the first, and I'm sure of that because I tested before). However, my result is:

  1) SimilarityMachine#answers_similarity when both answers have compilation error calls compiler_output_similarity method
     Failure/Error: expect(described_class).to receive(:compiler_output_similarity)

       (SimilarityMachine).compiler_output_similarity(*(any args))
           expected: 1 time with any arguments
           received: 0 times with any arguments

What am I doing wrong?

rwehresmann
  • 1,108
  • 2
  • 11
  • 27

1 Answers1

1

I would check out Testing modules in rspec other questions related to testing modules.

I'm not completely clear on this, but in general, modules don't receive method calls. They are collections of methods that have to be "mixed in" through the extend method and the like.

Here's an example how to test a module method in isolation, taken from https://semaphoreci.com/community/tutorials/testing-mixins-in-isolation-with-minitest-and-rspec:

describe FastCar
  before(:each) do
    @test_obj = Object.new
    @test_obj.extend(Speedable)
  end

  it "reports the speed" do
    expect(@test_obj.speed).to eq "This car runs super fast!"
  end
end
Community
  • 1
  • 1
Peter Alfvin
  • 28,599
  • 8
  • 68
  • 106