LoginSignup
1
0

More than 3 years have passed since last update.

非Active Record(Active Model)のデータをFactoryBotで生成する

Posted at

最近書いたテストが、ActiveModel(非アクティブレコード)に基づいていました。ちょっと工夫も必要だったので、備忘も兼ねて記事を残そうと思います。
今回テストを書いたモデルはこんな感じです。

Recordsモデル(非Active Record)

column type
id integer
title string
information text

テスト用のモデルを作る

spec/support/models/record.rb に以下のように記載し、テストに使えるモデルを作成します。

spec/support/models/record.rb
class Record
  attr_accessor :id, :title, :information
end

ファクトリを生成する

spec/factories/record.rb にファクトリを生成します。
class名を省略せずに入れるところがポイントです。

spec/factories/record.rb

FactoryBot.define do
  factory :record, class: :record do
    id { 1 }
    name { 'タイトルです' }
    information { 'テストデータです' }
  end
end

テストで使う

テストで使うときはこんな感じです。FactoryBot.create ではなく、FactoryBot.build を使うのがポイントです。(DBにテーブルがあるわけではないので、createでsaveまで走らせようとするとエラーになります)

 describe 'something', type: :something do
   redord = FactoryBot.build(:record)
   expect(record.title).to eq "タイトルです"
 end

結局、作成したテストではActiveModelのFactoryを使わなかったのですが、役に立ちそうだったので記録として残しておきます。

参考サイト:
Tips for Using FactoryGirl Without an ORM
非ActiveRecordなテスト用データを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