public
Description: Makes tests easy on the fingers and the eyes
Home | Edit | New

Example macros

This is a repository of user contributed shoulda macros. Feel free to add your own to this list – either linking to a blog post (highly encouraged), or showing the code inline.

Paperclip


class UserTest < Test::Unit::TestCase
  should_have_attached_file :avatar
end

See this GIANT ROBOTS post for the full code.

acts_as_paranoid


class UserTest < Test::Unit::TestCase
  should_act_as_paranoid
end

class Test::Unit::TestCase
  def self.should_act_as_paranoid
    klass = model_class
    
    context "A #{klass.name}" do
      should "be paranoid (it will not be deleted from the database)" do
        klass.paranoid?
      end
    
      should "not have a value for deleted_at" do
        assert object = klass.find(:first)
        assert_nil object.deleted_at
      end
    
      context "when destroyed" do
        setup do
          assert object = klass.find(:first)
          @deleted_id = object.id
          object.destroy
        end
      
        should "not be found" do
          assert_raise(ActiveRecord::RecordNotFound) { klass.find(@deleted_id) }
        end
    
        should "still exist in the database" do
          deleted_object = klass.find_with_deleted(@deleted_id)
          assert_not_nil deleted_object.deleted_at
        end
      end
    end
  end
end

RESTful AuthSystem (should_require_login)

See MetaSkills post for the full code.


class UsersControllerTest < ActionController::TestCase
  
  should_require_login :edit, :update, :etc
  
end

module AuthSystem
  module TestHelper
    
    def self.included(receiver)
      receiver.extend ClassMethods
      receiver.send :include, InstanceMethods
    end
    
    module ClassMethods
      
      def should_require_login(*actions)
        actions.each do |action|
          should "Require login for '#{action}' action" do
            get(action)
            assert_redirected_to(login_url)
          end
        end
      end
      
    end
    
    module InstanceMethods
      
      def login_as(user)
        if u = users(user)
          @request.session[:user_id] = u.id
        end
      end
      
    end
    
  end
end

Acts As Ferret, Acts As Taggable On Steroids, Acts As List

Some basic macros for acts_as_ferret, acts_as_taggable_on_steroids, and acts_as_list can be found at Shoulda Macros for Common Plugins – mileszs.com

Userstamp

See Rahvin’s post for the full code.


Class PostTest < Test::Unit::TestCase
  should_be_stampable
end

Class UserTest < Test::Unit::TestCase
  should_stamp_models
end
Last edited by cwalcott, Mon Aug 31 14:37:06 -0700 2009
Home | Edit | New
Versions: