开发者

With rspec, can I mock an object that is inside the method I am testing?

I have d开发者_运维百科efined the following method:

def some_method

  x = x + 1
  y = some_other_method(x)


  x + y
end

Now in my rspec spec, can I mock the call to some_other_method for my unit test for some_method?


You can indeed mock out other methods in a RSpec test. If the two methods you mentioned are inside a class, Foo, you would do something like this to make sure that some_other_method is called:

subject{ Foo.new }
it "should do whatever you're testing" do
  subject.should_receive(:some_other_method).and_return(5)
  subject.some_method
end

If you don't need to assert that is was called, just assert the results of some_method, you can do something like this instead:

subject{ Foo.new }
it "should do whatever you're testing" do
  subject.stub(:some_other_method).and_return(5)
  subject.some_method.should eq(6)
end

The above examples assume you're using RSpec 2. If you're using RSpec 1, you'll need to use stubs instead of stub.

If your methods are defined outside of a class, they're really defined on the class Object, so just use Object instead of Foo in the examples above.

For more information about mocks in RSpec, check out http://relishapp.com/rspec/rspec-mocks for RSpec 2 or http://rspec.info/documentation/mocks/ for RSpec 1.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜