RSpec Mock Object Example RSpec Mock Object Example ruby ruby

RSpec Mock Object Example


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_successend

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

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  endend


mock is deprecated based on this github pull.

Now instead we can use double - more here...

 before(:each) do   @page = double("Page")   end  it "page should return hello world" do    allow(@page).to receive(:say).and_return("hello world")    answer = @page.say    expect(answer).to eq("hello world")  end


I don't have enough points to post a comment to an answer but I wanted to say that the accepted answer also helped me with trying to figure out how to stub in a random value.

I needed to be able to stub an object's instance value that is randomly assigned for example:

class ClumsyPlayer < Player do  def initialize(name, health = 100)    super(name, health)    @health_boost = rand(1..10)  endend

Then in my spec I had a problem on figuring out how to stub the clumsy player's random health to test that when they get a heal, they get the proper boost to their health.

The trick was:

@player.stub!(health_boost: 5)

So that stub! was the key, I had been just using stub and was still getting random rspec passes and failures.

So thank you Brian