Skip to content

Instantly share code, notes, and snippets.

@adomokos
Created April 15, 2011 03:50
Show Gist options
  • Save adomokos/921111 to your computer and use it in GitHub Desktop.
Save adomokos/921111 to your computer and use it in GitHub Desktop.
This code is to demonstrate how I use test doubles for Rails.
class TracksController < ApplicationController
def index
signed_in_user
end
def new
@track = Track.new
end
def create
feed = params[:track]["feed"]
@track = TrackParserService.parse(feed)
unless @track.valid?
render :action => 'new'
return
end
@track.save_with_user!(signed_in_user)
render :action => 'index'
end
def destroy
Track.find(params[:id]).destroy
@user = User.first
render :action => 'index'
end
private
def signed_in_user
# No authentication yet
@user ||= User.first
end
end
APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), "..", "..", ".."))
$: << File.join(APP_ROOT, "app/controllers")
# A test double for ActionController::Base
module ActionController
class Base
def self.protect_from_forgery; end
end
end
class User; end
class Track; end
class TrackParserService; end
require 'application_controller'
require 'tracks_controller'
describe TracksController do
let(:controller) { TracksController.new }
specify "index action returns the signed in user" do
# setup
user = stub
User.stub(:first).and_return user
# execute action under test
returned_user = controller.index
# verify
returned_user.should == user
controller.instance_variable_get(:@user).should == user
end
specify "new action returns an instance of Track" do
# setup
track = stub
Track.stub(:new).and_return track
# execute action under test
new_track = controller.new
# verify
new_track.should == track
controller.instance_variable_get(:@track).should == track
end
context "when the model is not valid" do
it "renders action => 'new'" do
# define a method for params - TracksController is not aware of it
controller.class.send(:define_method, :params) do
{:track => "feed"}
end
track = stub(:valid? => false)
TrackParserService.stub(:parse).and_return(track)
render_hash = {}
# hang on to the input hash the render method is invoked with
# I'll use it to very that the render argument is correct
controller.class.send(:define_method, :render) do |hash_argument|
render_hash = hash_argument
end
controller.create
# verify the render was called with the right hash
render_hash.should == { :action => 'new' }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment