Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec Mock Object Example

I am new to mock objects, and I am trying to learn how to use them in RSpec. Can someone please post an example (a hello RSpec Mock object world type example), or a link (or any other reference) on how to use the RSpec mock object API?

like image 929
ab217 Avatar asked Sep 01 '10 22:09

ab217


People also ask

How do you mock an object in RSpec?

Just check for the return value. If the method is working with external objects & sending orders to them, then you can mock the interactions with these objects. If the method is REQUESTING data from an external service (like an API), then you can use a stub to provide this data for testing purposes.

How does a mock work in RSpec?

Mocking helps us by reducing the number of things we need to keep in our head at a given moment. Mocking with RSpec is done with the rspec-mocks gem. If you have rspec as a dependency in your Gemfile , you already have rspec-mocks available.

What is stubbing in RSpec?

In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet.

How does a mock work in Ruby?

Mocks are a handy tool for writing tests in Ruby. You can use them to fake an object and verify that the correct methods were called against it. Perfect for testing a method that integrates closely with another class or module.


1 Answers

Here's an example of a simple mock I did for a controller test in a rails application:

before(:each) do   @page = mock_model(Page)   @page.stub!(:path)   @page.stub!(:find_by_id)   @page_type = mock_model(PageType)   @page_type.stub!(:name)   @page.stub!(:page_type).and_return(@page_type) end 

In this case, I'm mocking the Page & PageType models (Objects) as well as stubbing out a few of the methods I call.

This gives me the ability to run a tests like this:

it "should be successful" do   Page.should_receive(:find_by_id).and_return(@page)   get 'show', :id => 1   response.should be_success end 

I know this answer is more rails specific, but I hope it helps you out a little.


Edit

Ok, so here is a hello world example...

Given the following script (hello.rb):

class Hello   def say     "hello world"   end end 

We can create the following spec (hello_spec.rb):

require 'rubygems' require 'spec'  require File.dirname(__FILE__) + '/hello.rb'  describe Hello do   context "saying hello" do      before(:each) do       @hello = mock(Hello)       @hello.stub!(:say).and_return("hello world")     end      it "#say should return hello world" do       @hello.should_receive(:say).and_return("hello world")       answer = @hello.say       answer.should match("hello world")     end   end end 
like image 111
Brian Avatar answered Nov 09 '22 13:11

Brian