Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Support refering to factory based on class name

Allows for build/creating based on RSpec's described_class, useful since
we've deprecated other syntaxes from FG.

Closes #386
  • Loading branch information...
commit f83c27e15d00beff864be32bf89c6beac33ae0df 1 parent e8d32b9
@joshuaclayton joshuaclayton authored
View
1  lib/factory_girl.rb
@@ -38,6 +38,7 @@
require 'factory_girl/reload'
require 'factory_girl/decorator'
require 'factory_girl/decorator/attribute_hash'
+require 'factory_girl/decorator/class_key_hash'
require 'factory_girl/decorator/disallows_duplicates_registry'
require 'factory_girl/decorator/invocation_tracker'
require 'factory_girl/decorator/invocation_ignorer'
View
27 lib/factory_girl/decorator/class_key_hash.rb
@@ -0,0 +1,27 @@
+module FactoryGirl
+ class Decorator
+ class ClassKeyHash < Decorator
+ def [](key)
+ @component[symbolized_key key]
+ end
+
+ def []=(key, value)
+ @component[symbolized_key key] = value
+ end
+
+ def key?(key)
+ @component.key? symbolized_key(key)
+ end
+
+ private
+
+ def symbolized_key(key)
+ if key.respond_to?(:to_sym)
+ key.to_sym
+ else
+ key.to_s.underscore.to_sym
+ end
+ end
+ end
+ end
+end
View
8 lib/factory_girl/registry.rb
@@ -6,7 +6,7 @@ class Registry
def initialize(name)
@name = name
- @items = {}
+ @items = Decorator::ClassKeyHash.new({})
end
def clear
@@ -19,7 +19,7 @@ def each(&block)
def find(name)
if registered?(name)
- @items[name.to_sym]
+ @items[name]
else
raise ArgumentError, "#{@name} not registered: #{name}"
end
@@ -28,11 +28,11 @@ def find(name)
alias :[] :find
def register(name, item)
- @items[name.to_sym] = item
+ @items[name] = item
end
def registered?(name)
- @items.key?(name.to_sym)
+ @items.key?(name)
end
end
end
View
22 spec/acceptance/keyed_by_class_spec.rb
@@ -0,0 +1,22 @@
+require 'spec_helper'
+
+describe 'finding factories keyed by class instead of symbol' do
+ before do
+ define_model("User") do
+ attr_accessor :name, :email
+ end
+
+ FactoryGirl.define do
+ factory :user do
+ name 'John Doe'
+ sequence(:email) {|n| "person#{n}@example.com" }
+ end
+ end
+ end
+
+ it 'allows interaction based on class name' do
+ user = FactoryGirl.create User, email: 'person@example.com'
+ user.email.should == 'person@example.com'
+ user.name.should == 'John Doe'
+ end
+end
View
8 spec/factory_girl/registry_spec.rb
@@ -57,4 +57,12 @@
subject.clear
subject.count.should be_zero
end
+
+ it "registers classes" do
+ define_class("User")
+ subject.register(User, registered_object)
+ subject.to_a.should == [registered_object]
+ subject.find(:user).should == registered_object
+ subject.find(User).should == registered_object
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.