LoginSignup
0
0

More than 1 year has passed since last update.

テストコードの記述 Rails

Posted at

どうやらエンジニアの開発現場では機能実装とテストコードの記述はセットで行われるらしい。

ただ残念ながら、私のポートフォリオは先に機能実装を全部してしまった。

しかしテストコードは記述する意味はある。

モデルとコントローラーでテストする。

テストコードは大きく、モデルとコントローラーの二つです。

導入

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'rspec-rails', '~> 4.0.0' #ここを追加
end

いつも通り、bundle install

で、

% rails g rspec:install

これで必要なディレクトリとファイルが作成されます。

--require spec_helper
--format documentation #追記

これで、テストの結果がターミナル上で表示されます。

"" コントローラーのテスト

% rails g rspec:request コントローラー名

で必要なファイルが作成されます。

spec/requests/archives_spec.rb
require 'rails_helper'

RSpec.describe "Archives", type: :request do
  describe "GET /archives" do
    it "Archivesページにアクセスすると正常にリクエストが返ってくる" do
      get archive_index_path
      expect(response).to have_http_status(200)
    end
    it "Archivesページにワード検索フォームが存在する" do
      get archive_index_path
      expect(response.body).to include('アーカイブを検索する')
    end
    it "Archivesページにタグ検索フォームが存在する" do
      get archive_index_path
      expect(response.body).to include('タグで絞り込み検索')
    end
    it "ArchivesページにHOMEボタンが存在する" do
      get archive_index_path
      expect(response.body).to include('HOME')
    end
  end
end

簡単に説明すると

have_http_status(200)

これで正常にアクセスできたかどうか

expect(response.body).to include('HOME')

これで、該当のページに正常に要素が存在するかどうかを判断します。

テスト実行時

% bundle exec rspec spec/requests/コントローラー名_spec.rb

また内容を確認するときはbinding.pryを使用しましょう。

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