rspec中未定义的函数错误

时间:2015-04-09 20:09:41

标签: ruby 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

我遇到第三个测试'加法器'时出现此错误:

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)>' 

似乎加法器的定义与rspec中的先前方法完全相同,所以我不确定是怎么回事。我已经检查过关于此的各种其他帖子,但是没有找到任何可以帮助我的东西,或者至少我理解足以帮助我。

1 个答案:

答案 0 :(得分:1)

测试中的函数(adder)尚未定义,正如规范失败所述。定义它可能是你锻炼的一部分。要定义它,请添加

def adder
end
05_silly_blocks.rb中的

,无论是在当前代码之前还是之后。

(需要更多才能让第三个例子通过,但是由于你已经通过了前两个例子,你可能会知道该怎么做。)