RailsとMinitest まとめ
MinitestとRSpecについて比較
Minitest
- 処理速度が速い。
- 元からついている機能が少ないので、拡張する必要がある。
- ピュアRuby
- 最初からいろんな機能が全部入ってて便利。(多機能)
- 記述がDSL(可読性良)
Railsテスティングガイドの要約(Minitest)
require "test_helper" class ArticleTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
上記のコードの説明をしていく。
require "test_helper"
↑
テストで使うデフォルト設定。
このファイルに追加したメソッドはテスト全体で使える。
class ArticleTest < ActiveSupport::TestCase
↑ ArticleTestクラスはActiveSupport::TestCaseを継承することによって、テストケース(test case)をひとつ定義している。これにより、ActiveSupport::TestCaseのすべてのメソッドをArticleTestで利用できる。
ArticleTest < ActiveSupport::TestCase < Minitest::Test
↑という風にMinitest::Testを継承しているので
test ブロック または、 test_で始まるメソッド名で、テストを定義できる。
assert true
↑アサーションとは、オブジェクトまたは式を評価して、期待された結果が得られるかをチェックするコード
以下のようなチェックを行うことができる。
- ある値が別の値と等しいかどうか
- このオブジェクトはnilかどうか
- コードのこの行で例外が発生するかどうか
- ユーザーのパスワードが5文字より多いかどうか
エラーの表示内容
F
↑テストが失敗している
E
↑テストコードで、エラーが発生している。
テスト例1 : システムテスト (indexページにh1が存在しているか)
システムテストとは
アプリケーションのユーザー操作のテストに使える。
$ bundle exec rails g system_test articles
↓
require "application_system_test_case" class ArticlesTest < ApplicationSystemTestCase test "viewing the index" do visit articles_path assert_selector "h1", text: "Articles" end end
テスト例2 : システムテスト続き (ボタンをクリック、値を入力など)
test "should create Article" do visit articles_path click_on "New Article" fill_in "Title", with: "Creating an Article" fill_in "Body", with: "Created this article successfully!" click_on "Create Article" assert_text "Creating an Article" end
テスト例3 : 結合テスト (ルートにアクセスして、h1タグの中身が"Welcome#index"かどうか調べる)
結合テストとは
複数のコントローラ同士のやりとりをテストする。
$ bundle exec rails g integration_test blog_flow
↓
require "test_helper" class BlogFlowTest < ActionDispatch::IntegrationTest test "can see the welcome page" do get "/" assert_select "h1", "Welcome#index" end end
テスト例4 : 結合テスト (ブログに新しい記事を1件作成して、生成された記事が表示できてるか?)
test "can create an article" do get "/articles/new" assert_response :success post "/articles", params: { article: { title: "can create", body: "article successfully." } } assert_response :redirect follow_redirect! assert_response :success assert_select "p", "Title:\n can create" end
まとめ
以上の、テスト例くらいの内容は抑えておきたいな〜。