Browse the Ruby on Rails Community.

You are here: Browse Railsplugins Test Exemplars

Test Exemplars

This plugin is based off of Piers Cawley’s post at http://www.bofh.org.uk/articles/2007/08/05/doing-the-fixture-thing. It allows you to easily create valid ActiveRecord objects for use in testing.

Usage is really simple. In your test_helper.rb or spec_helper.rb file just require “test_exemplars” include ExemplarBuilder

This provides you with the exemplify method that you can use to create an exemplar for any AR class.

Your best bet is to take a look at spec/test_exemplars_spec.rb to grok the usage. Here are a couple examples though. Assume the following ActiveRecord class:

class Chicken < ActiveRecord::Base
  attr_protected :ssn
end
  1. Basic exemplar with attributes exemplify Chicken, :name => “chicken little”, :age => 10 Chicken.exemplar => #<chicken:0×31227f0>”chicken little”, “ssn”=>nil, “age”=>10}, @new_record=true>
  1. Override attributes exemplify Chicken, :name => “chicken little”, :age => 10 Chicken.exemplar(:name => “amazing”) => #<chicken:0×3120374>”amazing”, “ssn”=>nil, “age”=>10}, @new_record=true>

exemplify also takes an optional block. This is useful for methods you need to call on the exemplar. For example, attr_protected attributes can’t be mass-assigned, you need to explicitly set them. Of course you can use it for any object initialization that isn’t basic hash attributes.

  1. ssn is ignored because of attr_protected exemplify Chicken, :ssn => “abc123” Chicken.exemplar => #<chicken:0×31377b8>nil, “ssn”=>nil, “age”=>nil}, @new_record=true>
  1. ssn is assigned in a block exemplify(Chicken) {|c| c.ssn = “abc123” } Chicken.exemplar => #<chicken:0×3136e1c>nil, “ssn”=>”abc123”, “age”=>nil}, @new_record=true>

Finally, you can automatically populate a field’s value with an autoincrementing exemplar ID.

  1. auto populate name field exemplify Chicken, :auto_id => :name Chicken.exemplar => #<chicken:0×311d638>”Chicken1”, “ssn”=>nil, “age”=>nil}> Chicken.exemplar => #<chicken:0×311d638>”Chicken2”, “ssn”=>nil, “age”=>nil}>

You can also automatically save the record with ARClass.create_exemplar and ARClass.create_exemplar!. They’re just convenience methods that build an exemplar and call #save and #save! respectively.

NOTE: This description has been extracted from the Plugin README and so the formatting may need updating to make browser friendly

Users


See all details


Membership

+ Join this railsplugin

Record Maintainer

'None'