我在一些项目中有一个功能启用机制(一个使用带有Rails 2的RSpec 1,另一个带有RSpec 2 / Rails 3),我正在寻找一种更好的方法来覆盖一个功能,必须对其他功能做任何事情。最终我正在寻找一种方法来在使用特定参数调用方法时对其进行存根,并且在其他方面正常运行。
关闭:
Project::Config.should_receive(:feature_enabled?).with('new_feature').any_number_of_times.and_return(true)
get :index # calls feature_enabled? for a few other features too
>> <Project::Config (class)> expected feature_enabled? with 'new_feature' but received it with 'some old feature'
工作,但我正在寻找一些更清洁的东西,特别是在不同级别的{}块之前可能有一些能够实现不同功能的情况下。
Project::Config.should_receive(:feature_enabled?).with('new_feature').any_number_of_times.and_return(true)
# expect any other calls
Project::Config.should_receive(:feature_enabled?).any_number_of_times
# I can't override any features here. This is annoying if I try to set up expectations at a few different levels
get :index # might call feature_enabled? for a few features
这也失败了:
Project::Config.stub(:feature_enabled?).with('new_feature').and_return(true)
get :index
>> undefined method `feature_enabled?' for Project::Config:Class
理想情况下,我可以在一行中做一些不影响其他feature_enabled的事情吗?调用。如果有一些适用于RSpec2的东西很好,因为我们会在某个时候更新另一个项目。
答案 0 :(得分:3)
我发现调用原始方法的最佳解决方案是这样的:
method = Project::Config.method(:feature_enabled?)
Project::Config.stub(:feature_enabled?).and_return do |arg|
method.call(arg)
end
Project::Config.should_receive(:feature_enabled?).with('new_feature').and_return(true)
答案 1 :(得分:0)
这是RSpec 3中可用的也许更干净的替代方法。
allow(Project::Config).to receive(:feature_enabled?).and_wrap_original do |method, arg|
case arg
when 'new_feature'
true
else
method.call(arg)
end
end
如果知道只需要一种情况,那么也可以使用三元甚至简单的||
:
allow(Project::Config).to receive(:feature_enabled?).and_wrap_original do |method, arg|
arg == 'new_feature' || method.call(arg)
end