class A
def initialize
@x = do_something
end
def do_something
42
end
end
Run Code Online (Sandbox Code Playgroud)
do_something
在调用原始实现之前,如何在rspec中存根(因此分配42 @x
)?当然,并没有改变实施.
Ori*_*rds 22
这是将功能添加到rspec的提交 - 这是在2008年5月25日.你可以这样做
A.any_instance.stub(do_something: 23)
Run Code Online (Sandbox Code Playgroud)
但是,rspec的最新宝石版本(1.1.11,2008年10月)中没有此补丁.
该票证明由于维护原因他们将其拉出,并且尚未提供替代解决方案.
看起来你不能在这一点上做到这一点.您将不得不使用alias_method或其他人手动破解该类.
Den*_*hev 16
我在http://pivotallabs.com/introducing-rr/上找到了这个解决方案
new_method = A.method(:new)
A.stub!(:new).and_return do |*args|
a = new_method.call(*args)
a.should_receive(:do_something).and_return(23)
a
end
Run Code Online (Sandbox Code Playgroud)
Dus*_*tin 11
我不知道如何在spec的模拟框架中执行此操作,但您可以轻松地将其替换为mocha来执行以下操作:
# should probably be in spec/spec_helper.rb
Spec::Runner.configure do |config|
config.mock_with :mocha
end
describe A, " when initialized" do
it "should set x to 42" do
A.new.x.should == 42
end
end
describe A, " when do_something is mocked" do
it "should set x to 23" do
A.any_instance.expects(:do_something).returns(23)
A.new.x.should == 23
end
end
Run Code Online (Sandbox Code Playgroud)