0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】テストについて

Posted at
Page 1 of 2

テストの種類

単体テスト モデルやビューヘルパー単体の動作をチェック
機能テスト コントローラ/ビューの呼び出し結果をチェック
統合テスト ユーザーの実際の操作を想定し、複数のコントローラにまたがるアプリの挙動をチェック

単体テスト

Railsで行うテストの中で、最も基本的なテスト
アプリを構成するライブラリ(主にモデル)が、正しく動作するかをチェックする

test/models/user_test.rb
require 'test_helper'

class UserTest < ActiveSupport::TestCase

  def setup
    @user = User.new(name: 'Example User', email: 'user@example.com'
  end

  test "should be valid" do
    assert @user.valid?
  end
end

assertメソッド: 第1引数がtrueである場合、テストが成功したものとする
setupメソッド : テストが走る前にインスタンス変数の@userを宣言し、 validメソッドで有効性を確認

機能テスト

コントローラの動作や、ビューの出力をチェックするためのテスト
HTTPリクエストを擬似的に作成することで、アクションメソッドを実行し、HTTPステータスやテンプレート変数、最終的な出力の構造までを確認。また、ルーティングもチェック

app/controllers/users_controller.rb
class UsersController < ApplicationController

def create
  @user = User.new(user_params)
  if @user.save
  else
    render 'new'
  end
end

private

def user_params
  params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end
end
test/integration/users_signup_test.rb
require 'test_helper'
class UsersSignupTest < ActionDispatch::IntegrationTest

  test "invalid signup information" do
    get signup_path
    assert_no_difference 'User.count' do
      post users_path, params: { user: { name:  "",
                                         email: "user@invalid",
                                         password:              "foo",
                                         password_confirmation: "bar" } }
    end
    assert_template 'users/new'
  end
end
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?