开发者

Why can't you directly stub! mock objects?

I might be missing something completely obvious here, but why do I have to do this:

setup do
  @person = mock("person")
  @person.stub!(:name).and_return("david")
end

Instead of

@person = mock("person").stub!(:name).and_return("david")

What is mock("string") returning that doesn't allow it to be stubbed versus allowing @person to be stubbed? Is mock not returning an object (perhaps just modifying some internal hash table of mock'ed开发者_StackOverflow中文版 out functions and then returning a separate object?


Because the and_return call doesn't return the stub object. mock does.

First, in order to have a mock object to work with, you have to create the actual mock object and assign it to a variable. When you call mock("person").stub!... the mock object is lost in the call chain. Your chained version would only work if and_return returned the original mock object.


As Peter points out, @person is being assigned the value from and_return rather than the mock object. This turns out to be a Proc.

You could do this:

@person = mock("person").tap {|obj| obj.stub!(:name).and_return("david") }

Though all this is unnecessary since you can declare the stub right in the mock definition:

@person = mock("person", :name => "david")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜