thoughtbot / factory_girl
- Source
- Commits
- Network (85)
- Issues (22)
- Downloads (10)
- Wiki (4)
- Graphs
-
Branch:
master
click here to add a description
click here to add a homepage
-
0 comments Created 8 months ago by qrushShorthand for referencing sequences in Factory definitionsfeaturexReported by Eric Mill
#13 describes syntactic sugar for one-off sequences inside factory definitions. This request is to expand that, and allow for easy referencing of separately defined sequences.
Referencing a separately defined sequence by name:
Factory.define :user do |u| u.sequence :email, :user_email end Factory.sequence(:user_email {|n| "user#{n}@mail.com"}Auto-referencing a separately defined sequence by using the same name:
Factory.define :user do |u| u.sequence :email end Factory.sequence(:email) {|n| "user#{n}@mail.com"}And here's a crazier, but cooler idea at syntax, that assumes that a symbol passed as an attribute value refers to the name of a sequence:
Factory.define :user do |u| u.email :user_email end Factory.sequence(:user_email) {|n| "user#{n}@mail.com"}The last example would eliminate the need for supporting either of the first two.
Comments
Please log in to comment. -
3 comments Created 8 months ago by qrushUndefine or delegate common object methods on proxiesfeaturexReported by Joe Ferris
Proxy objects are responsible for returning values of previously defined attributes, but you can't reference "id" and other attributes that conflict with methods on Object.
Proxy should either undefine these methods so that method_missing is called, or directly delegate them to #get.
Comments
I've undefined type and id in: http://github.com/flori/factory_girl/tree/type-attribute
The type attribute is necessary in order to use rails' single table
inheritance feature. Unfortunately this collides with Ruby's deprecated
Kernel#type method and the Factory object's method missing isn't
triggered. This change undefines the type instance method in Factory and
fixes the problem.Factory.define :bar do |b| b.type 'Bar' end Factory.define :baz do |b| b.type 'Baz' endHi flori.
I tried out your patch by manually inserting your changes into my copy of Factory Girl 1.2.2. I can confirm that your patch worked like a charm! Thank you kindly.
Please log in to comment.Me too. The patch works. Please merge it into the master.
-
Reported by Erik
The method variable_name_to_class_name has code that translates, say, 'active_record/base' to ActiveRecord::Base. But when I tried to use this, I got a 'wrong constant name' error, because constant names can't contain colons.
You can just supply a :class option, but it would be easier not to. I'm planning to fix the code and document the shortcut.
Here's my fix: http://github.com/eostrom/factory_girl/tree/guess_classes_in_modules
Comments
-
0 comments Created 8 months ago by qrushfeaturexAdd an ability to define default strategy globallypatchxReported by Peter Suschlik
Branch on github: http://github.com/splattael/factory_girl/tree/global_default_strategy
It's like
:default_strategyoption but for all factories:Factory.global_default_strategy = :build Factory.define(:post) {} ... Factory(:post) # => like Factory.build(:post)No need for
:default_strategy => :buildevery time.Note:
I don't like the name global_default_strategy.
Factory.default_strategy = :buildwould be nicer but I didn't want to hack up the current default_strategy method.Comments
Please log in to comment. -
2 comments Created 8 months ago by qrushbugxfactories named with a module/class path can find the classpatchxReported by Alex Rothenberg
When I have a model class defined within a module FactoryGirl was unable to find the class correctly because it was not traversing down the module hierarchy.
The fix along with a spec that fails before and passes after are at http://github.com/alexrothenberg/factory_girl/commits/factories_for_classes_with_modules_patch
My scenario is that I have a model defined in a module
module BlogModels class Comment < ActiveRecord::Base end end
and want to define a factory for it like this
Factory.define 'blog_models/comment' do |comment| end
It fails with this error
1) NameError in 'Factory a factory defined with a module name should load the class defined inside the module' wrong constant name GroupingOfModels::Comment /Users/alexrothenberg/ruby/github/factory_girl/spec/../lib/factory_girl/factory.rb:304:in `const_get' /Users/alexrothenberg/ruby/github/factory_girl/spec/../lib/factory_girl/factory.rb:304:in `class_for' /Users/alexrothenberg/ruby/github/factory_girl/spec/../lib/factory_girl/factory.rb:58:in `build_class' ./spec/factory_girl/factory_spec.rb:306:
Patching the class_for method in factory.rb to go down the module hierarchy as it loads the class fixes the problem.
I hope this is not too much information in the ticket but I thought it was better to err with too much rather than too little :)
Thanks
AlexComments
I encountered similar problems and a ' wrong constant name' error.
Please log in to comment.
jameskilton
Wed Jan 06 11:16:56 -0800 2010
| link
+1 on this. The patch works fine monkey-patched into my test suite.
-
1 comment Created 6 months ago by joshuaclaytonbugxFactories with parents defined don't have access to parent attributes when defining an attribute within a blockpatchxWhen creating a factory that has a parent defined, attributes defined in blocks don't have scope to parent attributes because the parent's attributes haven't been added to the factory yet.
I've created a branch that resolves this incorrect behavior: http://github.com/joshuaclayton/factory_girl/commits/parent-attributes-in-attribute-blocks
Comments
Please log in to comment.
joshuaclayton
Mon Aug 10 11:48:06 -0700 2009
| link
Looks like it didn't pull in the Gist I created: http://gist.github.com/gists/165346
-
7 comments Created 6 months ago by roderickvdAdd support for singleton factoriesfeaturexSingleton factories are useful for creating unique instances, such as a fixed set of movie genres. The branch at http://github.com/roderickvd/factory_girl/tree/singletons adds the following syntax to do just that:
# Defines a new singleton Factory.define :comedy, :class => Genre, :singleton => true do |g| g.name 'Comedy' end
Because the singleton option is set on the factory, it works seamlessly for associations and all strategies.
Comments
So this creates a genre record named "Comedy" that is validated uniqueness of? Can't be deleted?
roderickvd
Mon Aug 24 01:26:29 -0700 2009
| link
You are right that it's validated uniqueness of. It could be deleted, but at any point in time there will be at most a single instance of "Comedy" as a genre record.
Singleton support would be very useful for any model that defines a single tree data structure. I would like to use this for setting up the CMS page root before a bunch of tests.
That would indeed be amazing and very useful. Is there any plans to add this to the main tree?
This change would be great. It has a simple and elegant syntax. I have documented my issues with this shortcoming here...
This proposed change would fully resolve the issue.
paulgillard
Sat Jan 30 15:29:39 -0800 2010
| link
I think support for singleton records would be very useful indeed. It would certainly absolve test code from having to manage such issues. Consider though a record which validates uniqueness of a date. Using the patch in its current form would require having to define a new factory for every possible date I may want to test against. Rather than caching proxy results based on factory name would it better to cache based on a combination of ActiveRecord class name, the unique attribute name/s (there may be more than one unique attribute on a model) and unique attribute values? This would also get around the issue of two different factories each defining a record with the same value for the unique attribute thus still causing the testing problems this issue was raised to fix.
Maybe something along the lines of:
Factory.define :comedy, :class => Genre, :singleton => [:name] do |g| g.name 'Comedy' endImplemented by:
def run (proxy_class, overrides) #:nodoc: proxy = proxy_class.new(build_class) overrides = symbolize_keys(overrides) overrides.each {|attr, val| proxy.set(attr, val) } passed_keys = overrides.keys.collect {|k| Factory.aliases_for(k) }.flatten @attributes.each do |attribute| unless passed_keys.include?(attribute.name) attribute.add_to(proxy) end end if singleton? singletons[class_name] ||= {} @options[:singleton].each do |attribute| singletons[class_name][attribute] ||= {} if cached_instance = singletons[class_name][attribute][proxy.get(attribute)] return cached_instance end end result = proxy.result @options[:singleton].each do |attribute| singletons[class_name][attribute][proxy.get(attribute)] = result end result else proxy.result end endIt's messy and could do with some refactoring but illustrates the idea.
Of course there's also the question of how much further one might want to go with this. What about validates_uniqueness_of :foo, :scope => :bar
Please log in to comment.
roderickvd
Sun Jan 31 05:26:22 -0800 2010
| link
The core team has informed me that they won't be adding this feature. Hence I'm no longer working on this patch.
They'd rather have that users chain db:seed to work with their Rake tasks. I think it's a good suggestion and hope that they'll add it to the documentation.
-
0 comments Created 5 months ago by sandropatchxbugxStubbing proxy fails on non-ActiveRecord classespatchxI've created a branch which makes the stubbing strategy more friendly for non-AR classes.
http://github.com/sandro/factory_girl/tree/stub_for_non_ar_objectsThe main issue is that the stubbing proxy calls #new which won't work if #initialize takes requires arguments. The fix is to fall back to #allocate when #new fails.
Comments
Please log in to comment. -
0 comments Created 5 months ago by arturazAllow accessing Factory.define options.featurexFactory.define :building, :class => Building::Mothership do |m|
m.x 0 m.x_end { |r| r.x + r.instance_variable_get("@instance").class.property('width') } endIt would be nice to just be able to
Factory.define :building, :class => Building::Mothership do |m|
m.x 0 m.x_end { |r, options| r.x + options[:class].property('width') } endComments
Please log in to comment. -
ActiveRecord and DataMapper share a significant amount of API. Enough at least to allow factory_girl to work with both. The following patch maintains compatibility.
Comments
I would also love to see DataMapper compatibility maintained. I've done some additional work to make the alternate syntaxes work with DM as well http://github.com/bgentry/factory_girl
The code works but there's an issue with DM not adding inclusions to Models if the models were loaded before the inclusion was added. I'm working to fix that in DataMapper right now.
Published a patch which should be included in the latest version of DataMapper, so my factory_girl changes above should be sufficient as soon as this commit is added to dm-core:
http://github.com/bgentry/dm-core/commit/2e64f793646040b55ce12bb43a3476cd4d661f04the changes are merged into DataMapper's dm-core master branch, which will become 0.10.2.
In the mean time, there is no harm in merging the work that startrader & I did. This will never work properly with older versions of DataMapper anyway.
Please log in to comment.DM 0.10.2 is out, append_inclusions works, so I think it's safe to merge your patches upstream.
I've also created 3 more patches:
removing "requiring" of activesupport in factory_girl.rb: http://github.com/sickill/factory_girl/commit/01ad2687ec9a1e97f005231932a7378ec5f279ae
adding additional dm-sweatshop-like syntax: http://github.com/sickill/factory_girl/commit/d965718aeee77af974418e710dd5dc493d951cc2 (it's need for following patch to apply)
updating alternate syntaxes to use extlib's "snakecase" method instead of activesupport's "underscore" when available: http://github.com/sickill/factory_girl/commit/2eb1533ad8b0bc69552eaee7536c8365d7f8e441
With these we got rid of activesupport completely.
-
Factory with parent fails inconsistently due to file load order
2 comments Created 4 months ago by webgetProblem: a factory define that has a parent seems to be failing because the parent isn't loaded yet.
Example:
test/factories/person.rb Factory.define :person do |p| p.name 'Joe' end test/factories/person_with_extras.rb Factory.define :person_with_extras, :parent => :person do |p| p.age 21 endUsing the code above gives this error: No such factory: person.
Is it correct that a factory can have a parent like this, in a different file?
When I look in the gem factory.rb, it seems that the load order is inconsistent on line 276:
Dir[File.join(path, '*.rb')].each do |file|
I would expect at least for the files to be in alphabetic order:
- Dir[File.join(path, '*.rb')].each do |file| + Dir[File.join(path, '*.rb')].sort.each do |file|
Is there something obvious that I'm missing?
Or is it supposed to be this way?
Could the Thoughtbot team at least add the "sort" to the file list?
Much obliged,
Joel Parker Henderson
joelparkerhenderson@gmail.comComments
stevenderocher
Wed Dec 16 11:07:44 -0800 2009
| link
Hi Joel,
In general we try to discourage relying on load order for success as it creates hard-to-track dependencies.
Please log in to comment.Definitely - but is that the reason for the exception, or might there be a different reason for the exception he is seeing? I see the same problem - an association that claims the other factory does not exist.
-
We've got quite a few namespaced models in our codebase, and so far we've had no troubles specifying factories for them like so:
factory :namespace_foo, :class => Namespace::Foo do |nsf| nsf.foo 'foo' nsf.bar 'bar' endHowever now working with Spork in our specs, I'm trying to prevent the constants from being loaded so early, so I changed all the constants to strings.
factory :namespace_foo, :class => 'Namespace::Foo' do |nsf| nsf.foo 'foo' nsf.bar 'bar' endBut now all my factories break with
NameError Exception: wrong constant nameThis is just a simple matter of changing the way that factory_girl calls
Object#const_get. I'm forking and I'll link a branch with the fix shortly.Comments
Please log in to comment.Test case and fix pushed to this branch:
http://github.com/phinze/factory_girl/commits/issue28_factory_class_with_namespaceOne commit for the test case: http://github.com/phinze/factory_girl/commit/ddedf312568a9c66dfe6c1eb1be0c0bffc6fc83f
Another for the fix: http://github.com/phinze/factory_girl/commit/06b7b065e2477094f4e04e5f4601489578910ef1 -
Factory.attributes_for incompatible with association syntax
0 comments Created about 1 month ago by tfwrightFactory.attributes_for(:appointment) => {:provider=>nil, :patient=>nil, :start_time=>"8:00", :end_time=>"10:00", :office=>nil}
but
Factory.build(:appointment).attributes => {"kind"=>nil, "end_time"=>Thu, 24 Dec 2009 10:00:00 UTC +00:00, "created_at"=>nil, "provider_id"=>101, "updated_at"=>nil, "patient_id"=>21, "appointment_date"=>nil, "description"=>nil, "start_time"=>Thu, 24 Dec 2009 08:00:00 UTC +00:00, "office_id"=>51}
Comments
Please log in to comment. -
Gemspec doesn't mention activesupport as dependency
4 comments Created about 1 month ago by ncrspec.add_dependency("activesupport") should be enough
Comments
Currently factory_girl core doesn't use activesupport at all. It used cattr_accessors at some time but it was replaced and activesupport dependency was removed from gemspec. Only alternate syntaxes use String#underscore method from ActiveSupport. However it is still being "required" in factory_girl.rb.
I'm using FG with Merb/DataMapper and I've made patches to FG in my fork, look here http://github.com/sickill/factory_girl/commit/01ad2687ec9a1e97f005231932a7378ec5f279ae and here http://github.com/sickill/factory_girl/commit/2eb1533ad8b0bc69552eaee7536c8365d7f8e441
Look at this issue also: http://github.com/thoughtbot/factory_girl/issues/#issue/22
I believe it still requires it in first line here:
http://github.com/thoughtbot/factory_girl/blob/master/lib/factory_girl.rbYes, it is. There are some patches for it, look at commits from my previous comment, and also at issue #22 I've mentioned.
Please log in to comment.My bad, I'm a bit dense today. Thanks for thorough answer.
-
[PATCH] :default_strategy should be inherited from parent
1 comment Created about 1 month ago by jtrupianoCurrently I have to specify :default_strategy => :build for every factory.
Comments
Please log in to comment.See my branch inherit_build_strategy for a patch: http://github.com/jtrupiano/factory_girl/commits/inherit_build_strategy
-
I have to redefine associations in factories, even if the parent factory defines them already.
Comments
Please log in to comment. -
Factories don't support primary_id being a string
0 comments Created 29 days ago by itsmeduncanExample:
Factory.define :product do |p| st.sequence(:id) { |n| "123456ABCDE#{sprintf("%04d", 1000+n)}"} st.price 200 endError:
ActiveRecord::RecordInvalid in 'Product Testing validations before(:all)' Validation failed: Product product_id.validates_presence_ofComments
Please log in to comment. -
[invalid] before_create, before_build, before_mock callbacks
1 comment Created 27 days ago by gabetaxI'm withdrawing this issue, as after reading the source it's become obvious that:
1) after_build is run when doing a .create, and is effectively the same thing as before_create
2) before_build and before_mock are not necessary, as there is not state change (like a .save) before .after_build and .after_mock would be run.Comments
-
The association section of the readme has a couple of typos in it.
Here's my fix: http://github.com/paulgillard/factory_girl/tree/readme_typo_fix
Comments
Please log in to comment.
paulgillard
Sun Jan 17 15:41:58 -0800 2010
| link
Also fixed typo in dependent attributes section. Added to same branch above.
-
Maintain a list of created objects for forensics when tests break.
0 comments Created 12 days ago by leehambleyHi,
Just sent a pull request for a small patch that keeps a list of generated objects in a cache so they can be forensically analysed on broken test runs.
I'm not sure if this is a valuable feature or not for the community, but please, review the patch ( http://github.com/leehambley/factory_girl/commit/feb72764c84fa76b31757f0c67f50f88262e3932 ) and I'd love some feedbac either way.
More info in the pull request that I sent, but that's not too important the code speaks for itself.
- Lee
Comments
Please log in to comment. -
Unable to use Factory Girl in a clean environment
3 comments Created 3 days ago by mbrungWe use factory_girl to populate our demo environments with representative test data (users, accounts, etc.). Often we like to
rake db:drop rake db:setupthen call our custom task to use our factories.
Problem is: after a db:drop there are no tables in the database, which prevents Factory Girl from loading the factory definitions -- and prevents us from pretty much doing anything. Quick workaround was to comment out the requirement for the factory_girl gem in environment.rb -- but I'd think it might be better to stop factory_girl from loading factory definitions when the db is blank,
What do you guys think?
Comments
Can you just call
Factory.find_definitionsin your custom task?Shouldn't you populate tables with data after creating the tables/schema? E.g.
rake db:drop db:create db:migrate db:populate_with_factory_girlPlease log in to comment.Oops, my bad: one of my factory definitions looked like
Factory.define :address do |a|
a.state State.find_by_state_abbreviation("AZ")end
which of course won't work if the State table doesn't exist... Replaced it with an after_build callback -- much happier now...
-
Not sure if this is a bug or my misunderstanding of how factory_girl works...docs and lib/factory_girl.rb suggest that factories autoloaded from:
test/factories.rb spec/factories.rb test/factories/*.rb spec/factories/*.rbComments and code in lib/factory_girl/factory.rb show "factories" should also be autoloaded.
Should
File.join(RAILS_ROOT, 'factories')be in lib/factory_girl.rb or am I reading this wrong?
In lib/factory_girl.rb:
if defined? Rails.configuration Rails.configuration.after_initialize do Factory.definition_file_paths = [ File.join(RAILS_ROOT, 'test', 'factories'), File.join(RAILS_ROOT, 'spec', 'factories') ] Factory.find_definitions end else Factory.find_definitions endIn lib/factory_girl/factory.rb
class << self attr_accessor :factories #:nodoc: # An Array of strings specifying locations that should be searched for # factory definitions. By default, factory_girl will attempt to require # "factories," "test/factories," and "spec/factories." Only the first # existing file will be loaded. attr_accessor :definition_file_paths end self.factories = {} self.definition_file_paths = %w(factories test/factories spec/factories)Comments
Please log in to comment.



