rspec 中的未定义函数错误

undefined function error in rspec

我在 运行 作为练习的一部分提供的 rspec 文件时遇到问题,我不确定发生了什么。

这是我在 silly_blocks.rb 中的代码:

def reverser(num = 1)
  result = []
  if yield == Integer
    yield + num
  else
    yield.split.each{|word| result << word.reverse}  
  result.join(' ')

  end

end

这是 rspec 文件:

require "05_silly_blocks"

describe "some silly block functions" do

  describe "reverser" do
    it "reverses the string returned by the default block" do
      result = reverser do
        "hello"
      end
      result.should == "olleh"
    end

    it "reverses each word in the string returned by the default block" do
      result = reverser do
        "hello dolly"
      end
      result.should == "olleh yllod"
    end
  end

  describe "adder" do
    it "adds one to the value returned by the default block" do
      adder do
        5
      end.should == 6
    end

    it "adds 3 to the value returned by the default block" do
      adder(3) do
        5
      end.should == 8
    end
  end

  describe "repeater" do
    it "executes the default block" do
      block_was_executed = false
      repeater do
        block_was_executed = true
      end
      block_was_executed.should == true
    end

    it "executes the default block 3 times" do
      n = 0
      repeater(3) do
        n += 1
      end
      n.should == 3
    end

    it "executes the default block 10 times" do
      n = 0
      repeater(10) do
        n += 1
      end
      n.should == 10
    end

  end

end

我在第三次测试时遇到这个错误'adder':

Failures:                                                                                                                                  

  1) some silly block functions adder adds one to the value returned by the default block                                                  
     Failure/Error: adder do                                                                                                               
     NoMethodError:                                                                                                                        
       undefined method `adder' for #<RSpec::ExampleGroups::SomeSillyBlockFunctions::Adder:0x007f334345b460>                               
     # ./p.rb:30:in `block (3 levels) in <top (required)>' 

似乎 adder 的定义方式与 rspec 中以前的方法完全相同,所以我不确定发生了什么。我已经查看了有关此的各种其他帖子,但没有找到任何可以帮助我的东西,或者至少我的理解足以帮助我。

测试中的函数 (adder) 尚未定义,正如规范失败所表明的那样。定义它可能是您练习的一部分。要定义它,添加

def adder
end

05_silly_blocks.rb 中,在当前代码之前或之后。

(要使第三个示例通过,还需要更多,但由于您已经通过了前两个示例,因此您可能会知道从那里该怎么做。)