valid model attribute factory test helpers

I like to use factory test helpers to generate attributes which I then pass to ActiveRecord. The default output is expected to be valid (hence the usage with create-bang below). If you want to override any of the defaults, you can simply use Hash#merge.

Here’s an example, using shoulda. It should be pretty clear how it can be applied to vanilla Test::Unit (or the testing framework du jour ;).


##  I put this in test_helper.rb so I can use it across all tests.
## You could put it in the actual derived test class as well.

  def valid_user_attrs( unique = DateTime.now )
    { :email => "{unique.hash.abs}@example.com", :first_name => "dummy", :last_name => "user_#{unique}", :profile_attributes => valid_profile_attrs }
  end

  def valid_profile_attrs
    ...
  end


## Here’s the actual test case
  
class UserTest < Test::Rails::TestCase

  context "Two Users" do
    setup do
      @user = User.create!( valid_user_attrs )
      @user2 = User.create!( valid_user_attrs.merge( :email => "dummy123@dummy.com" ) )
    end

    should "not be friends" do
      assert !@user.friends.include?( @user2 )
      assert !@user2.friends.include?( @user )
    end

  end
end

		
		
	

render a partial from inside a model

Have you ever wanted to render a partial to a string from inside a model?

This solution was inspired by this snippet showing how to use view helpers in a controller. It’s clean and simple, no need to mess with ERB or metaprogramming!


class Model

  class Helper < ActionView::Base
    include Singleton
  end
  def help
    Helper.instance
  end

  ...

  def summarize
    ## Note that we have to use the FULL path here!  
    help.render( :partial => "#{RAILS_ROOT}/app/views/notifications/text_order_summary", :object => self )
  end
  alias_method :to_s, :summarize

end

actionmailer ActionView ActiveRecord activesupport agile ajax alphadecimal audio autotest BDD blocks capistrano ssh ruby console controller css dashboard widget delegate dog puppy naming name DRM email obfuscation exceptions factories factories-and-workers factory pattern filemerge find and replace finder fink fixtures fun functional testing gem git google maps haml helper helpers imagemagick Intertrust irb javascript jquery jrails logo macro math meetup model openssl OS X patch Pioneer Electronics plugin polymorphism project management prototype.js rails rails gotcha rails,patch,validations railsconf rake rmagick RSA encryption ruby ruby on rails script scrum scrum lessons rails scrumninja shoulda subversion SyncTV TDD testing textmate tips tricks unique hashes unix shell validation view yaml zebra stripes