15
6

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入門ガイド

Last updated at Posted at 2024-07-08

こんにちは!この記事では、RubyのテストツールRSpecの使い方を超初心者の私が説明します。一緒にステップバイステップで学んでいきましょう!

目次

  1. RSpecって何?
  2. RSpecのインストール方法
  3. RSpecの基本的な使い方
  4. 実際にテストを書いてみよう!
  5. まとめ

1. RSpecって何?

RSpecは、Rubyというプログラミング言語で書いたコードが正しく動くかどうかをチェックするためのツールです。コードを書いた後に「ちゃんと動くかな?」と確かめる手助けをしてくれます。

2. RSpecのインストール方法

まず、RSpecを使うためにインストールします。以下のコマンドをターミナルで実行してみてください。

gem install rspec

Bundlerを使っている場合は、Gemfileに以下を追加してからbundle installを実行します。

group :test do
    ・・・
  gem 'rspec'
  ・・・
end

これでRSpecの準備が整いました!

3. RSpecの基本的な使い方

次に、プロジェクトのディレクトリで以下のコマンドを実行してRSpecを初期設定します。

rails generate rspec:install

これにより、RSpecの設定ファイルとディレクトリが作成されます。

手動でcontrollersディレクトリを作成したい場合

以下のコマンドを入力

mkdir -p spec/controllers

4. 実際にテストを書いてみよう!

まず、簡単な計算機のクラスをテストしてみます。calculator.rbというファイルを作って、以下のコードを書いてみてください。

# calculator.rb
class Calculator
  def add(a, b)
    a + b
  end
end

次に、specディレクトリの中にcalculator_spec.rbというファイルを作成し、以下のコードを書きます。

# spec/calculator_spec.rb
require 'rspec'
require_relative '../calculator'

RSpec.describe Calculator do
  it 'adds two numbers' do
    calculator = Calculator.new
    result = calculator.add(2, 3)
    expect(result).to eq(5)
  end
end

このコードでは、Calculatorクラスのaddメソッドが2つの数を正しく足し算するかどうかをテストしています。

テストを実行してみよう!

ターミナルで以下のコマンドを実行して、テストを実行してみましょう。

下記のコマンドは、インストールされている全てのRSpecのバージョンから最新のものを選んでテストを実行する。

rspec

すると、テストの結果が表示されます。

5.まとめ

今回は、RSpecの基本的な使い方を一緒に学びました。テストを書くことで、コードのバグを見つけやすくなり、品質を保つことができます。

15
6
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
15
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?