LoginSignup
6
2

More than 3 years have passed since last update.

Rails console でも FactoryBot のメソッド呼び出しを簡単にする

Posted at

Ruby on Rails + FactoryBot で開発をおこなっていると、Rails console を使ってサクッとデータを作成して REPL で検証したくなることがあります。この時 FactoryBot.create()FactoryBot.build() と書かなければならず、普段テストで書いている create()build() に比べると若干の面倒さが目立ってしまいます。

僕は怠惰なので以下のような hook を .pryrc に書いてこの問題を解決してみました。

# -*- mode: ruby -*-
Pry.hooks.add_hook(:before_session, "use FactoryBot shorthand") do |output, binding, pry|
  Object.include FactoryBot::Syntax::Methods
end

これでいつでも create(:user)build(:user) でユーザーを作成することができます。

なお、みなさんご想像の通りトップレベルに世界の開発者が想像もしないようなメソッドを生やすので世界が壊れるかもしれません :innocent:

6
2
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
6
2