agentbanks217 agentbanks217 - 1 year ago 133
Ruby Question

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?

Answer Source

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_type = mock_model(PageType)

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
  get 'show', :id => 1
  response.should be_success

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


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

Given the following script (hello.rb):

class Hello
  def say
    "hello world"

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")

    it "#say should return hello world" do
      @hello.should_receive(:say).and_return("hello world")
      answer = @hello.say
      answer.should match("hello world")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download