【发布时间】:2011-11-29 10:52:37
【问题描述】:
我是 TDD 和元编程的新手,所以请耐心等待!
我有一个 Reporter 类(用于包装 Garb ruby gem),当我点击 method_missing 时,它将即时生成一个新的报告类并将其分配给 GoogleAnalyticsReport 模块。主要要点如下:
# Reporter.rb
def initialize(profile)
@profile = profile
end
def method_missing(method, *args)
method_name = method.to_s
super unless valid_method_name?(method_name)
class_name = build_class_name(method_name)
klass = existing_report_class(class_name) ||
build_new_report_class(method_name, class_name)
klass.results(@profile)
end
def build_new_report_class(method_name, class_name)
klass = GoogleAnalyticsReports.const_set(class_name, Class.new)
klass.extend Garb::Model
klass.metrics << metrics(method_name)
klass.dimensions << dimensions(method_name)
return klass
end
Reporter 期望的“配置文件”类型是 Garb::Management::Profile。
为了在这个 Reporter 类上测试我的一些私有方法(例如 valid_method_name? 或 build_class_name),我想我想用 rspec 模拟配置文件,因为这不是我感兴趣的细节。
但是,对 klass.results(@profile) 的调用 - 正在执行并杀死我,所以我没有对我在元部分中扩展的 Garb::Model 进行存根。
到目前为止,我是这样模拟和存根的……规范的实现当然不重要:
describe GoogleAnalyticsReports::Reporter do
before do
@mock_model = mock('Garb::Model')
@mock_model.stub(:results) # doesn't work!
@mock_profile = mock('Garb::Management::Profile')
@mock_profile.stub!(:session)
@reporter = GoogleAnalyticsReports::Reporter.new(@mock_profile)
end
describe 'valid_method_name' do
it 'should not allow bla' do
@reporter.valid_method_name?('bla').should be_false
end
end
end
有谁知道我如何在我新创建的类上对 results 方法的调用存根?
任何指针将不胜感激!
~斯图
【问题讨论】:
标签: ruby rspec mocking metaprogramming