LoginSignup
0
0

【Ruby on Rails】FactoryBot,Fakerの導入

Posted at

各Gemの説明

① factory_bot_rails
model のデータに紐づいたテストデータを簡単に作るための gem です。
② faker
faker は、ダミーデータを作るのに便利な gem です。

Gemの導入方法

Gemfile
# 中略
group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'pry-byebug'
  gem 'pry-rails'
  gem 'rspec-rails'
+  gem 'factory_bot_rails'
+  gem 'faker'
end

# 中略

追加したら、bundle installを実行します。

各ファイルの修正

factory_bot_rails

spec/rails_helper.rb
# 中略

RSpec.configure do |config|
+  config.include FactoryBot::Syntax::Methods
# 中略
end

# 中略

上記のように修正することで、FactoryBot のメソッドを省略した形で呼び出すことができるようになります。

faker

spec/rails_helper.rb
+ Faker::Config.locale = :ja

上記の修正を行うことで、Fakerで作成されるダミーデータが日本語になります。

application.rbの修正

application.rb
    # 中略
    config.generators do |g|
      g.javascripts false
      g.stylesheets false
      g.helper false
      g.template_engine false
-      g.test_framework false
+      g.test_framework :rspec
    end
    # 中略
  end
end

modelやcontrollerを作成するタイミングでrspec のテストファイルも同時に作成されるようになります。
具体的には、bundle exec rails gを実行したときに、新しいmodel,contorollerファイルだけでなく、テストファイルも作成されます。

以上、FactoryBot,Fakerの導入でした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0