3章 テスト
はやくもテストの解説が出てきて嬉しい!
まずはrails generatorが作ってくれたテストだけ実行。
code:bash
sample_app $ rails test
Running via Spring preloader in process 21888
/Users/akiko/work/rails5/sample_app/db/schema.rb doesn't exist yet. Run rails db:migrate to create it, then try again. If you do not intend to use a database, you should instead alter /Users/akiko/work/rails5/sample_app/config/application.rb to limit the frameworks that will be loaded.
Run options: --seed 46659
# Running:
..
Finished in 1.920924s, 1.0412 runs/s, 1.0412 assertions/s.
2 runs, 2 assertions, 0 failures, 0 errors, 0 skips
失敗するテストを書く
実装していないactionのテストを書いて、GETで200番がくるかを確認
結果は失敗しますが、ルーティングがないのか、コントローラがわのエラーなのかはわかりません
code:ruby
test "should get about" do
get static_pages_about_url
assert_response :success # successでなければ失敗
end
テストの結果はこの通り。
code:bash
sample_app $ rails test
Running via Spring preloader in process 22216
.....
Run options: --seed 65259
# Running:
E
Error:
StaticPagesControllerTest#test_should_get_about:
test/controllers/static_pages_controller_test.rb:15:in `block in <class:StaticPagesControllerTest>'
# routingの確認
sample_app $ bin/rails routes
Prefix Verb URI Pattern Controller#Action
static_pages_home GET /static_pages/home(.:format) static_pages#home
static_pages_help GET /static_pages/help(.:format) static_pages#help
メッセージをよく読むと、about へのURLが無いということになります。
実際に、ブラウザでアクセスすると、まずはroutingが無いことがわかります。
https://gyazo.com/1ada4026c029748b1c1a250eb40f3f80
ルーティングを追加してみる
では、routingにaboutへのURLを追加してみます。
code:ruby
Rails.application.routes.draw do
get 'static_pages/home'
get 'static_pages/help'
get 'static_pages/about' # 追加
end
今度はメッセージが変わりました。でも失敗。コントローラに対するアクションが無いと言われています。
テストっぽい!!
code:bash
sample_app $ rails test
Running via Spring preloader in process 22735
Run options: --seed 24561
# Running:
E
Error:
StaticPagesControllerTest#test_should_get_about:
AbstractController::ActionNotFound: The action 'about' could not be found for StaticPagesController
test/controllers/static_pages_controller_test.rb:15:in `block in <class:StaticPagesControllerTest>'