【Ruby on Rails】ユニットテストをする
Ruby on Railsでテストをしたい。
テストはrakeで行うようです。
$ rake
Run options: --seed 9253 # Running tests: .............. Finished tests in 1.049915s, 13.3344 tests/s, 24.7639 assertions/s. 14 tests, 26 assertions, 0 failures, 0 errors, 0 skips
とテストが実行されます。
まだテストを書いていないので何も起きません。
userテーブルに対してテストを書いていきます。
# vim test/models/user_test.rb
userテーブルには2つだけレコードが入っていますが
わざと99個にしてみます。
require 'test_helper' class UserTest < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end # usersテーブルは99のデータが入っているか test "test_data_count" do user=User.all assert_equal 99 ,user.length end end
# rake
Run options: --seed 34206 # Running tests: .......F........ Finished tests in 0.346363s, 46.1944 tests/s, 80.8402 assertions/s. 1) Failure: UserTest#test_test_data_count [<PATH_TO_APP>/test/models/user_test.rb:12]: Expected: 99 Actual: 2 16 tests, 28 assertions, 1 failures, 0 errors, 0 skips
Failureが出ました。
正しく動くように書き換えます
※16testsと出てるのは他でテスト書いてるためです
require 'test_helper' class UserTest < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end # usersテーブルは2つのデータが入っているか test "test_data_count" do user=User.all assert_equal 2 ,user.length end end
# rake
Run options: --seed 59983 # Running tests: ................ Finished tests in 0.276852s, 57.7927 tests/s, 101.1372 assertions/s. 16 tests, 28 assertions, 0 failures, 0 errors, 0 skips
無事テストが通りました。
このようにしてテストを書いていきます。