1
1

Rspec ざっくりチートシート

Posted at

Rspec チートシート

0. 前提要件

テストを始める前に、以下の要件が満たされていることを確認しましょう。

  • Railsプロジェクト: Rspec-railsはRailsのプロジェクト専用のgemです。新しいRailsプロジェクトはrails new [プロジェクト名]で作成できます。
  • Bundler: Rubyの依存関係管理ツール。Gemfileに記述されたgemをインストールする際に使用します。Railsをインストールすると、Bundlerも一緒にインストールされます。

次に、RSpecのインストールや基本的なコマンドなどの情報をチートシートとしてまとめます。

1. セットアップ

# Gemfileに追加
gem 'rspec-rails', group: :development, :test

# Rspecをインストール
$ bundle install
$ rails generate rspec:install

2. Userモデルのテスト

expect文でuserがvalid?メソッドを実行した場合を確認しています。
valid?メソッドが定義されたバリデーションを満たしているかどうかをチェックします。

RSpec.describe User, type: :model do
  it "is valid with a name, email, and password" do
    user = User.new(name: "Alice", email: "alice@example.com", password: "password")
    expect(user).to be_valid
  end
end

3. UsersControllerコントローラのテスト

getやpostなどのテストも可能です。

#getのテスト
RSpec.describe UsersController, type: :controller do
  describe "GET #index" do
    it "responds successfully" do
      get :index
      expect(response).to be_successful
    end
  end
end

#postのテスト
RSpec.describe UsersController, type: :controller do
  describe "POST #create" do
    #テストデータ作成
    let(:valid_attributes) {
      { name: "Alice", email: "alice@example.com", password: "password" }
    }

    it "creates a new user with valid attributes" do
      expect {
        post :create, params: { user: valid_attributes }
      }.to change(User, :count).by(1)
    end

    it "redirects to the new user's page after creation" do
      post :create, params: { user: valid_attributes }
      expect(response).to redirect_to(user_path(User.last))
    end
  end
end


4. FactoryBotの使用

❶FactoryBotはテストデータの生成をサポートするgemです。
❷テストの際にテストデータを一部をオーバーライド(変更)することなどが可能です。
❸describeやcontextの下などに使用例にあるような形でテストデータを定義します。

# Gemfileに追加
gem 'factory_bot_rails'

# factories/users.rb
FactoryBot.define do
  factory :user do
    name { "Alice" }
    email { "alice@example.com" }
    password { "password" }
  end
end

# テストでの使用例
let(:user) { create(:user) }

5. it / describe / context

contect itの中身は文章っぽくなるとわかりやすいです。
「When user is logged in it shows the user's profile」

describe "GET #index" do
  context "when user is logged in" do
    it "shows the user's profile" do
      # テスト内容
    end
  end
end
1
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
1
1