LoginSignup
76
57

More than 3 years have passed since last update.

FactoryBotをrails consoleから使う

Last updated at Posted at 2016-02-24

はじめに

既にFactoryBotをRailsで利用している人向けのお話です。

rails consoleでちょっと試したいことがあるけど、インスタンスの生成が面倒なモデルがあったりします。
FactoryBotでフィクスチャーが用意されていれば、それを使った方が手っ取り早いです。

しかし、rails consoleを立ち上げただけではFactoryBotは使えません。

手順

rails consoleはSandboxモードで立ち上げたほうがデータベースが汚れなくてよいでしょう。

$ rails console test --sandbox

(RAILS_ENVdevelopmentのときにもFactoryBotが有効になるようにしていればtestは不要です)

FactoryBotをrequireします。

require 'factory_bot_rails'

FactoryBotクラス名を明示せずにcreatebuildを行えるようにします。(オプション)

include FactoryBot::Syntax::Methods

これでrails consoleからFactoryBotが使えるようになります。

おまけ

コピペしてまとめて流す用のまとめです。

require 'factory_bot_rails'
include FactoryBot::Syntax::Methods

参考

76
57
4

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
76
57