我正在嘗試使用簡單的遞歸階乘在Ruby中執行TDD。我正試圖運行一個簡單的測試,但我一直運行到一個NoMethodError。我想知道我做錯了什麼?嘗試在Ruby中進行測試驅動開發時出現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
但我結束了一個NameError:
`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
是不是有什麼毛病我初始化階乘的方式類?
謝謝!我得到了這個錯誤,但是當我應用修復時,我得到了一個新的錯誤,它說'NoMethodError:undefined method'factorial'for nil:NilClass'。我是否正確設置了它? – user3369494
我很肯定你現在已經弄明白了,但是你應該調用你的setup方法來設置實例變量,然後你可以調用該實例變量的方法。 – hackrnaut