尝试在Ruby中进行测试驱动开发时出现NoMethodError

时间:2016-09-26 15:12:14

标签: ruby minitest

我试图用简单的递归因子在Ruby中做TDD。我试图运行一个简单的测试,但我一直遇到NoMethodError。我想知道我做错了什么?

这是我的factorial_test.rb

require 'minitest/autorun'
require './factorial.rb'

class FactorialTest < MiniTest::Test
  describe Factorial do
    it "should provide factorial of 1 as 1" do
      factorial(1).must_equal 1
    end
  end
end

这是我的factorial.rb

class Factorial 
  def factorial(number)
    1
  end
end

但我一直收到错误:

`NoMethodError: undefined method `factorial' for #<#<Class:0x007fbaa5962d70>:0x007fbaa584a758>`

我甚至尝试将设置部件添加到我的factorial_test.rb中,如下所示:

require 'minitest/autorun'
require './factorial.rb'

class FactorialTest < MiniTest::Test
  def setup
    @factorial = Factorial.new
  end

  describe Factorial do
    it "should provide factorial of 1 as 1" do
      factorial.factorial(1).must_equal 1
    end
  end
end

但我最终得到了一个N​​ameError:

`NameError: undefined local variable or method `factorial' for #<#<Class:0x007fc0e8996fc8>:0x007fc0e90ef1f8>`

如果有人能帮助我,我会很感激!

编辑:

应用以下建议中的修复:

describe Factorial do
    it "should provide factorial of 1 as 1" do
      @factorial.factorial(1).must_equal 1
    end
  end

我得到了一个不同的错误:

NoMethodError: undefined method `factorial' for nil:NilClass

我正在初始化阶乘类的方式有问题吗?

2 个答案:

答案 0 :(得分:2)

您正在创建一个实例变量:

def setup
    @factorial = Factorial.new
end

但是你在一个局部变量上调用你的测试:

it "should provide factorial of 1 as 1" do
     factorial.factorial(1).must_equal 1
end

尝试在您创建的实例变量上调用测试:

it "should provide factorial of 1 as 1" do
    @factorial.factorial(1).must_equal 1
end

答案 1 :(得分:1)

你的直觉在正确的轨道上!

#factorial是一个实例方法,因此需要在实例上调用(又名Factorial.new)。

您在设置方法中设置@factorial = Factorial.new的更改是正确的,现在您只需要在@factorial上调用该方法:

@factorial.factorial(1).must_equal 1

您收到undefined local variable or method 'factorial',因为该变量的名称为@factorial,而不只是factorial。你需要@