0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

RSpec FactoryBotについて

Posted at

はじめに

Railsでテストをする際に使用するRSpec FactoryBotの基本的な使い方を備忘を含め書きたいと思います。
間違いなどありましたらコメントお願いいたします。

RSpecとは

RSpecは、Rubyや Railsの代表的なテストフレームワークの一つです。

特徴

describeやcontextでテスト構造を定義
itを使ってテストケースを定義
expectを使って期待する結果を検証

こちらの記事がとてもわかりやすかったです。

FactoryBotとは

FactoryBotは、テストデータを簡単に作成するためのライブラリです。データベースに手動でレコードを作成する手間を省くことができます。

FactoryBotの使い方

テストデータの作成

spec/factories/の階層にUserモデルならusers.rbという形でファイルを作成します

FactoryBot.define do
  factory :user do
    name { "テストユーザ" }
    email { "test@example.com" }
  end
end

テストデータの使用

RSpecのテストで作成したデータを使用します。
このRSpecのコードは、Userモデルのインスタンスがバリデーションを通過するかをテストしています。

RSpec.describe User, type: :model do
  it "ユーザーが有効であること" do
    user = FactoryBot.build(:user)
    expect(user).to be_valid
  end
end

letを使用する場合

createとbuildの違い

let(:user) { FactoryBot.create(:user) } # データベースに保存
let(:user) { FactoryBot.build(:user) } # メモリ上のオブジェクト

RSpecとFactoryBotを活用すると、テストデータの作成が簡単になり、テストの可読性や保守性が向上します。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?