# rspecでテストを書き直す

記述してきたテストを見ながらrspecに置き換えていきましょう。

### rspecを使ったTicTacToeValidatorTestを実装する

以前に実装したtic\_tac\_toe\_validator\_test.rbの内容を参考にrspec版を新しく作成していきます。

specフォルダにtic\_tac\_toe\_validator\_spec.rbを作成してください。

(rspecの場合、xxx\_testでなくxxx\_specと書きます)

### rspecを使ったテストの実装

早速、rspecを使ってTicTacToeValidatorTestを記述してみます。

```ruby
require 'rspec'
require_relative "../tic_tac_toe/tic_tac_toe_validator"
require_relative "../tic_tac_toe/errors/tic_tac_toe_input_error"

RSpec.describe "3目並べのバリデーションに関してテスト" do

  context "ユーザからの入力値に誤りがある場合" do 

    it "意図したエラークラスの返却" do
      expect { TicTacToeValidator.validate_input_value!("a", "0") }.to raise_error(TicTacToeInputError, "行番号の入力に誤りがあります")
      expect { TicTacToeValidator.validate_input_value!("4", "0") }.to raise_error(TicTacToeInputError, "行番号の入力に誤りがあります")
      expect { TicTacToeValidator.validate_input_value!("0", "a") }.to raise_error(TicTacToeInputError, "列番号の入力に誤りがあります")
      expect { TicTacToeValidator.validate_input_value!("0", "4") }.to raise_error(TicTacToeInputError, "列番号の入力に誤りがあります")
    end

  end

  context "ユーザからの入力値に誤りがない場合" do 

    it "エラーが返却されないことを担保" do
      expect { TicTacToeValidator.validate_input_value!("0", "0") }.not_to raise_error
      expect { TicTacToeValidator.validate_input_value!("2", "2") }.not_to raise_error
    end

  end

end
```

テストのタイトルや動きが日本語で記述され分かりやすくなりました。

テストコードもスッキリしています。

### rspecの実行

コンテナの中に入って以下のコマンドを叩きます。

```
rspec spec
```

実行すると以下のような画面になると思います。

```
3目並べのバリデーションに関してテスト
  ユーザからの入力値に誤りがある場合
    意図したエラークラスの返却
  ユーザからの入力値に誤りがない場合
    エラーが返却されないことを担保

Top 2 slowest examples (0.00122 seconds, 14.3% of total time):
  3目並べのバリデーションに関してテスト ユーザからの入力値に誤りがある場合 意図したエラークラスの返却
    0.00117 seconds ./spec/tic_tac_toe_validator_spec.rb:9
  3目並べのバリデーションに関してテスト ユーザからの入力値に誤りがない場合 エラーが返却されないことを担保
    0.00005 seconds ./spec/tic_tac_toe_validator_spec.rb:20

Finished in 0.00856 seconds (files took 0.07446 seconds to load)
2 examples, 0 failures
```

rspecが気に入ったらminitestで記述していた他のテストコードも置き換えていきましょう。

以下のリポジトリに掲載されているテストコードを参考にして作ってみてください。

{% embed url="<https://github.com/Kashiwara0205/ruby-tic-tac-toe/tree/master/ch-rspec/code/spec>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kashiwara.gitbook.io/rubydesurufurusukuratchibe/omake-rspecwottatesuto/rspecdetesutowokisu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
