<pre><code>class A
  def initialize
    @x = do_something
  end

  def do_something
    42
  end
end
</code></pre>

<p>How can I stub <code>do_something</code> in rspec, before the original implementation is called (thus assigning 42 to <code>@x</code>)? And without changing the implementation, of course.</p>

I don't know how to do that in spec's mock framework, but you can easily swap it out for mocha to do the following:
```
```
# 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
```
```