1
0
Fork 0
mirror of https://github.com/thoughtbot/factory_bot.git synced 2022-11-09 11:43:51 -05:00

Added a Sham syntax layer

This commit is contained in:
Joe Ferris 2009-02-17 14:06:20 -05:00
parent 47b6ca0342
commit 03b3f9200f
2 changed files with 80 additions and 0 deletions

View file

@ -0,0 +1,40 @@
class Factory
module Syntax #:nodoc:
# Adds a Sham module, which provides an alternate interface to
# Factory::Sequence.
#
# Usage:
#
# require 'factory_girl/syntax/sham'
#
# Sham.email {|n| "somebody#{n}@example.com" }
#
# Factory.define :user do |factory|
# factory.email { Sham.email }
# end
#
# Note that you can also use Faker, but it is recommended that you simply
# use a sequence as in the above example, as factory_girl does not provide
# protection against duplication in randomized sequences, and a randomized
# value does not provide any tangible benefits over an ascending sequence.
module Sham
module Sham #:nodoc:
def self.method_missing(name, &block)
if block_given?
Factory.sequence(name, &block)
else
Factory.next(name)
end
end
# overrides name on Module
def self.name(&block)
method_missing('name', &block)
end
end
end
end
end
include Factory::Syntax::Sham

40
test/syntax/sham.rb Normal file
View file

@ -0,0 +1,40 @@
require 'test_helper'
require 'factory_girl/syntax/sham'
class ShamSyntaxTest < Test::Unit::TestCase
context "a factory" do
setup do
Sham.name { "Name" }
Sham.email { "somebody#{rand(5)}@example.com" }
Factory.define :user do |factory|
factory.first_name { Sham.name }
factory.last_name { Sham.name }
factory.email { Sham.email }
end
end
teardown do
Factory.factories.clear
Factory.sequences.clear
end
context "after making an instance" do
setup do
@instance = Factory(:user, :last_name => 'Rye')
end
should "support a sham called 'name'" do
assert_equal 'Name', @instance.first_name
end
should "use the sham for the email" do
assert_match /somebody\d@example.com/, @instance.email
end
end
end
end