我试图将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"
答案 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