开发者

How can fixtures be replaced with factories using rails3-generators?

I'm trying to replace fixture generation with factories using rails3-generators:

https://github.com/indirect/rails3-generators#readme

The gem is included in my Gemfile and has been installed:

# Gemfile
gem 'rails3-generators', :group => :development

I added the following to application.rb:

# application.rb
config.generators do |g|
  g.stylesheets false
  g.fixture_replacement :factory_girl
end

Yet 'rails g model Insect' is still generating fixtures ('insects.yml'). Is this working for others using Rails 3.0.4 and rails3-generators 0.17.4?

'rails g' shows the new generators available (such as Authlogic and Koala), but 'rails g model' still lists fixtures and doesn't refer to factories.

What else sh开发者_Go百科ould I add to get this to work? Thanks.

Edit: I ran the gem's test suite, which includes a test for this, and it passes. No clue why it doesn't work with my app.

Edit2: I tried again with a test project and get the same result: fixtures instead of factories. If anybody could confirm whether this works for them with Rails 3.0.4 and rails3-generators 0.17.4, that would be helpful too because it would imply that I'm doing something wrong with my projects.

Edit3: It works if I run 'rails g model Insect -r factory_girl'. I thought the generator configuration in application.rb was supposed to take care of that, so this seems to be the source of the problem.


Searching around I found the following, which may help:

  1. Try specifying a directory option for factory_girl's factories:

    config.generators do |g|
      g.stylesheets false
      g.fixture_replacement :factory_girl, :dir => "spec/factories" # or test/factories, as the case may be
    end
    
  2. If you're using Test::Unit, try the following:

    config.generators do |g|
      g.stylesheets false
      g.test_framework  :test_unit, :fixture_replacement => :factory_girl
    end
    

In both cases you will still need the rails3-generators gem, although there is a push to get that functionality into factory_girl_rails.

This Rails bug indicates that, at some point, the g.fixture_replacement code may not have worked right. Perhaps a test in 3.0.5 is in order. :)


A short update 9 years later:

instead of "factory_girl_rails" (which is deprecated now) use "factory_bot_rails".

Now, the factory gets created automagically:

$ rails g model tester name:string

Running via Spring preloader in process 31467

 invoke  active_record

 create    db/migrate/20200327152901_create_testers.rb

 create    app/models/tester.rb

 invoke    rspec

 create      spec/models/tester_spec.rb

 invoke      factory_bot

 create        spec/factories/testers.rb

I use rails 5.2.4, but this should also work with rails 6.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜