Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'test/unit'
require 'rubygems'
require 'shoulda'
require 'factory_girl'
require 'dm-core'
require 'dm-validations' # Needed for save!
class User
include DataMapper::Resource
property :id, Serial
property :name, String
property :key, String
property :domain, String
property :email, String
has 1, :gizmo
def self.generate_key
'BONK'
end
end
class Gizmo
include DataMapper::Resource
property :id, Serial
property :name, String
property :user_id, Integer
belongs_to :user
end
DataMapper.setup(:default, :adapter => 'in_memory')
Factory.sequence :gizmo_name do |n|
"widget#{n}"
end
Factory.define(:user) do |u|
u.name 'Adam'
u.key { User.generate_key }
u.domain 'example.com'
u.email { |u| "#{u.name.downcase}@#{u.domain}" }
end
Factory.define(:thingy, :class => Gizmo) do |g|
g.name 'Thingy'
g.user { |user| user.association(:user, :domain => 'foo.com') }
end
Factory.define(:doodad, :class => Gizmo) do |d|
d.name 'Doodad'
d.association :user, :factory => :user
end
Factory.define(:widget, :class => Gizmo) do |w|
w.name Factory.next(:gizmo_name)
w.association :user
end
class TestUser < Test::Unit::TestCase
def teardown
User.all.destroy!
Gizmo.all.destroy!
end
should 'build a user' do
user = Factory.build(:user)
assert_equal 'Adam', user.name
end
should 'create a user' do
user = Factory(:user)
assert !user.dirty?
end
should 'have a lazy-generated key' do
user = Factory.build(:user)
assert_equal 'BONK', user.key
end
should 'have a dependent email address' do
user = Factory.build(:user)
assert_equal 'adam@example.com', user.email
end
should 'create a user with a dependent gizmo' do
gizmo = Factory(:thingy)
assert_equal 'Adam', gizmo.user.name
end
should 'create a user with a dependent gizmo via syntactic sugar' do
gizmo = Factory(:doodad)
assert_equal 'Adam', gizmo.user.name
end
should 'use a sequence to generate a widget' do
Factory(:widget)
Factory(:widget)
gizmo = Factory(:widget)
assert_equal 3, Gizmo.all.length
assert_match /widget/, gizmo.name
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.