Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

ruby - 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?

question from:https://stackoverflow.com/questions/3622604/rspec-mock-object-example

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...