LoginSignup
1
0

More than 3 years have passed since last update.

RailsじゃないRspecで書かれたテストに途中からFactoryGirl導入する時の小技

Last updated at Posted at 2019-11-07

背景

Railsではない環境で書かれたRspecにFactoryGirlを導入して?ってぶん投げられたとき

既存のspec_helperの設定を変えずに新しく作ったfactory有のspecファイルの設定を分けたい。

shared_contextの活用

Factoryを使用するspecと使用しないspecでshared_contextを分けて定義する。

/spec/spec_helper.rb
shared_context 'Factory init', :factory_init => true do
  RSpec.configure do |config|
    # factory method
    config.include FactoryGirl::Syntax::Methods

    # factory path
    FactoryGirl.definition_file_paths = [File.expand_path('/home/imada/rails_app/spec/factories/', __FILE__)]
    FactoryGirl.find_definitions
  end
end

このshared_contextを定義することで既存specとfactoryを使用したspecとで設定を分けることができる。

後は実際のspecファイル内で

実際のテストspec
RSpec.describe "factory test", :factory_init => true do
end

を記述すればOK

まとめ

RailsじゃないRspecの情報が少なすぎて自分でどうにかするしかない。

途中でFactoryGirl導入して?って渡されたときはこの記事を有効活用してください。(そんなことないと思うけど)

1
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
1
0