我有父类
class StatsPeriod::Base
def merge(data)
to_range.inject({}) do |result, date|
result[date] = data[date] || 0
result
end.to_a
end
end
这是我的规格
require "rails_helper"
describe StatsPeriod::Base do
let(:data) { { "20160604" => 1, "20160601" => 2 } }
let(:range_data) do
[
"20160528",
"20160529",
"20160530",
"20160531",
"20160601",
"20160602",
"20160603",
"20160604"
]
end
describe "#merge" do
let(:stats) do
[
["20160528", 0],
["20160529", 0],
["20160530", 0],
["20160531", 0],
["20160601", 2],
["20160602", 0],
["20160603", 0],
["20160604", 1]
]
end
it "returns hash with stats" do
expect(described_class.new.merge(data)).to eq(stats)
end
end
end
如何模拟只存在于子类中的方法to_range
并返回range_data
或者我应该模拟子类并期望类似ChildClass.merge(数据)但
答案 0 :(得分:0)
不仅仅是这个吗?
it "returns hash with stats" do
fred=described_class.new
allow(fred).to receive(:to_range) { range_data}
expect(.merge(data)).to eq(stats)
end
答案 1 :(得分:0)
Ruby + monkey-patching = win:)
如果需要,您可以打开该类并添加该方法的实现以便进行测试。为了防止全局范围,最好使用优化 http://ruby-doc.org/core-2.1.1/doc/syntax/refinements_rdoc.html
module M
refine StatsPeriod::Base do
def to_range
...
end
end
end
然后你可以打电话
using M
在你的规范中将猴子补丁纳入范围?