16
Mocking & Stubbing FOR GREAT JUSTICE!

Mocking & Stubbing

Embed Size (px)

Citation preview

Mocking & StubbingFOR GREAT JUSTICE!

It’s About Context

Don’t Get It Wrong

For Additional Reading• Dependency Inversion Principle

• Liskov Substitution Principle

• Dependency Injection

• Law of Demeter

• “Tell, Don’t Ask”

MockingCreating Fake Things

Mockingbook = double("book") book = instance_double("Book", :pages => 250)notifier = class_double("ConsoleNotifier")user = object_double(User.new, :save => true)

Mockinghttp://www.relishapp.com/rspec/rspec-mocks/docs

StubbingDoing Fake Things

Stubbing

dbl = double("Some Collaborator")

allow(dbl).to receive(:foo)expect(dbl).to receive(:foo)

Stubbing

dbl = double("Some Collaborator")

allow(dbl).to receive(:foo) {…}expect(dbl).to receive(:foo) {…}

Stubbing

dbl = double("Some Collaborator")

allow(dbl).to receive(:foo).with(some_args) {…}expect(dbl).to receive(:foo).with(some_args) {…}

Stubbinghttp://www.relishapp.com/rspec/rspec-mocks/docs

Mocking & StubbingIt’s Dangerous…It’s Difficult…But…

Some AdviceIgnore At Your Peril

Some Advice• allow_any_instance_of is an almost sure sign you’re doing it wrong.

• expect_any_instance_of is the same.

• If you create more than a couple doubles you’ve probably found something with a high degree of coupling

• If you create more than a couple stubs per discreet test, you’re probably asking for too much

• Some kinds of classes will almost always exhibit a high degree of coupling — View/Form Objects — Everything else is definitely a code smell