Difference between Mocks and Stubs in RSpec

Stub

A stub is the only defined result of the method call which doesn’t care about behavior. With RSpec, you can use stub with allow and receive methods.

allow(object).to receive(:method_name)

If you need to stub the result of the method then it’s possible with and_return

allow(object).to receive(:method_name).and_return(example_value)

Mock

Mock expect methods to be called, otherwise it raises an error. With RSpec, you can use mock with expect and receive methods.

expect(object).to receive(:method_name)

As well as the stub replacing mock result possible with and_return

expect(object).to receive(:method_name).and_return(example_value)

Double

Test double is a dummy object that you use to replace a real object during a test. Through RSpec, you can create it with the double method.

describe UpdateObject do
let(:external_api) { double }
before do
allow(ExternalApi).to recieve(:new).and_return(external_api)
allow(external_api).to recieve(:some_api_call)
end
it 'returns success' do
expect(subject.call).to eq(:success)
end
end

In the example above we are using fake double object created to replace API call inside UpdateObject and avoid dependence of the test on the work of an external service.

If you want to create a more specified test, you can replace double with instance_double, which will fail tests if the class or object doesn’t have used methods.

--

--

--

Software Engineer. Interested in Full-Stack Development and DevOps.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Cracked the Code

What is Twelve-Factor App Methodology In Web App Development?

Apache Airflow Tutorial — ETL/ELT Workflow Orchestration Made Easy

Github Actions & AWS

10 Simple VS Code Extensions for Everyday Use

How to Check if a Given Key Already Exists in a Dictionary

Web Factory becomes part of the Pangea universe

Operations to Development Journey Episode 1

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kirill Shevchenko

Kirill Shevchenko

Software Engineer. Interested in Full-Stack Development and DevOps.

More from Medium

Rails: Routing & Custom Rendering

Linking Dependent Updates Across Multiple Tables in Ruby on Rails

Process incoming emails in Rails 6 with Action Mailbox : from development to production

How to Use Drag And Drop On HTML5 Canvas Element Using FabricJS