rails generateでFactoryGirl Fixtures

2014-07-30T00:00:00+00:00 Ruby Rails

※Gemfileでenvironmentにおける依存性で:developmentを指定していればこういう設定しなくても良い模様

参考: http://stackoverflow.com/questions/11702265/can-factorygirl-generate-factories-after-your-models-have-been-created

普通に

rails g model user

なんてやると

invoke      active_record
create      db/migrate/20140730063528_create_users.rb
create      app/models/user.rb
invoke      test_unit
create      test/models/user_test.rb
create      test/fixtures/users.yml

っていうようにtest/fixturesな所にfixtureなあれが生成される。でRSpecで且つFactoryGirlを使うようなケースだとconfig/application.rbに設定しとけば良いっぽい

require File.expand_path("../boot", __FILE__)

require "rails/all"

Bundler.require(*Rails.groups)

module Sample
  class Application < Rails::Application
    # 以降追加
    config.generators do |g|
      g.test_framework :rspec, fixture: true
      g.fixture_replacement :factory_girl, dir: "spec/factories"
    end
  end
end

なんていう設定して

rails g model user

のコマンドを再度行うと

invoke          active_record
identical       db/migrate/20140730063528_create_users.rb
identical       app/models/user.rb
invoke          rspec
create          spec/models/user_spec.rb
invoke          factory_girl
create          spec/factories/users.rb

っていうようにfixtureの出力先がspec/factoriesになりつつ、FactoryGirlなFixtureスクリプトが生成される模様。ちなみにfixture_replacementを設定しないでtest_frameworkだけを:rspecで設定した場合には、spec/fixturesにyamlファイルが生成される

Capybaraで複数のセッションを使う strong parameters