向Ruby Array开放类添加方法

时间:2016-04-04 01:36:59

标签: ruby

我试图将all_empty?方法添加到核心Ruby Array类中,如下所示:

class Array
  def all_empty?
    ...
  end
end

不幸的是,以下测试失败了:

require "spec_helper"

describe Array do
  context "#all_empty?" do
    it "returns true if all elements of the Array are empty" do
      expect(["", "", ""].all_empty?).to be_truthy
    end
  end
end

我得到以下NoMethodError:

NoMethodError:
   undefined method `all_empty?' for ["", "", ""]:Array
   Did you mean?  empty?
 # ./spec/core_extensions_spec.rb:6:in `block (3 levels) in <top (required)>'

如何让规范识别出我已经定义了all_empty?方法?

编辑:这是以下评论中要求的spec_helper.rb文件内容:

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require_relative "../lib/tic_tac_toe.rb"

1 个答案:

答案 0 :(得分:0)

您应该将require文件放入您的规范中,以获取您为此数组定义的方法(all_empty?)。或者你可以在spec_helper.rb

中要求它

默认情况下,rspec会将您的本地lib目录添加到加载路径中。

让它说在lib/array_method.rb

class Array
  def all_empty?
    ...
  end
end

现在,您应该require这个

require `array_method`

describe Array do
  context "#all_empty?" do
    it "returns true if all elements of the Array are empty" do
      expect(["", "", ""].all_empty?).to be_truthy
    end
  end
end

spec_helper.rb

require `array_method`

然后

您的规范代码

require "spec_helper"

describe Array do
  context "#all_empty?" do
    it "returns true if all elements of the Array are empty" do
      expect(["", "", ""].all_empty?).to be_truthy
    end
  end
end