Rspec没有找到类方法

时间:2017-07-21 15:23:13

标签: ruby rspec

我正在为我的后端工作编写一些测试,而且我有一个奇怪的问题,rspec没有找到我的方法。

我写了一个简单的课程&测试来说明问题:

app / interactors / tmp_test.rb:

class TmpTest
  def call
    a = 10
    b = 5
    b.substract_two
    return a + b
  end

  def substract_two
    c = self - 2
    return c
  end
end

spec / interactors / tmp_test.rb:

require 'rails_helper'

describe TmpTest do
  context 'when doing the substraction' do
    it 'return the correct number' do
      expect(described_class.call).to eq(13)
    end
  end
end

输出:

TmpTest
  when doing the substraction
    return the correct number (FAILED - 1)

Failures:

  1) TmpTest when doing the substraction return the correct number
     Failure/Error: expect(described_class.call).to eq(13)

     NoMethodError:
       undefined method `call' for TmpTest:Class
     # ./spec/interactors/tmp_test.rb:6:in `block (3 levels) in <top (required)>'

Finished in 0.00177 seconds (files took 1.93 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/interactors/tmp_test.rb:5 # TmpTest when doing the substraction return the correct number

2 个答案:

答案 0 :(得分:1)

它不是类方法,它是一个实例方法。您的测试应该如下所示:

describe TmpTest do
  subject(:instance) { described_class.new }

  context 'when doing the subtraction' do
    it 'returns the correct number' do
      expect(instance.call).to eq(13)
    end
  end
end

答案 1 :(得分:0)

这是一个完整的混乱。已修正的评论版本:

class TmpTest
  def call
    a = 10
    b = 5
    # b.substract_two # why do you call method of this class on b?!
    a + subtract_two(b)
  end

  def substract_two(from)
    from - 2
  end
end

另外:不要在方法的最后一行使用return