测试是否在模块方法中调用方法

时间:2017-01-23 15:12:53

标签: ruby-on-rails rspec

我的模块中有以下内容:

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

我想测试这些" if条件",以确保调用正确的方法(所有这些方法都来自SimilarityMachine模块)。为此,我有:

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

创建了两个答案后,我转到右侧if(第一个,我确信这是因为我之前测试过)。但是,我的结果是:

  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

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我会查看updateHandler与测试模块相关的其他问题。

我对此并不完全清楚,但一般情况下,模块不接收方法调用。它们是必须通过extend方法等“混合”的方法集合。

以下是一个如何从Testing modules in 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