Mocking with Mocha

Software testers often substitute mock objects for real-world implementations that may be difficult to test or use. Ruby makes mocking easy because you can add a substitute for any method. This technique makes it easy to play “what if” when you are testing. If you wonder what would happen if a test should fail, you could replace the complicated save method with a method that does nothing but return false.

Rails supports several different mocking frameworks. In this chapter, we’re going to use Mocha to change the behavior of some parts of our application to make it easier to test. To install the Mocha gem, do the following:

$ sudo gem install mocha
Password:
Successfully installed mocha-0.5.6
1 gem installed
Installing ri documentation for mocha-0.5.6...
Installing RDoc documentation for mocha-0.5.6...

Next, install it as a plug-in:

$ script/plugin install svn://rubyforge.org/var/svn/mocha/trunk
...
Exported revision 313.

Now, we’re going to use Mocha to fill some gaps in the test coverage. Take a second look at the create method in the photos controller:

  def create
    @photo = Photo.new(params[:photo])

    respond_to do |format|
      if @photo.save
        flash[:notice] = 'Photo was successfully created.'
        format.html { redirect_to(@photo) }
        format.xml  { render :xml => @photo, :status => :created, :location => @photo }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @photo.errors, :status => :unprocessable_entity }
      end
    end
  end

The uncovered part of this method ...

Get Rails: Up and Running, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.