初投稿。
曲がりなりにも2年Rails使ってるのにテスト書いたことないの恥ずかしすぎるし、徐々にでいいからテスト書いていこうね運動実施中。
というわけで既存のmodelに対する簡単なテストを作ってみたら、Mysqlに怒られた。
やったこと
Rails + minitestでテスト作成。
db/migrate/20151112145702_create_users.rb
1 class CreateUsers < ActiveRecord::Migration
2 def change
3 create_table :users do |t|
4 t.string :name, null: false
5 t.string :email, null: false
6 t.index [:name, :email], unique: true
7
8 t.timestamps null: false
9 end
10 end
11 end
こういう感じで作られたtableがあって、
$ rails g minitest:model user
create test/models/user_test.rb
create test/fixtures/users.yml
こんな感じでコマンドラインからtestを作ると、
test/model/user_test.rb
1 require "test_helper"
2
3 class UserTest < ActiveSupport::TestCase
4 def user
5 @user ||= User.new
6 end
7
8 def test_valid
9 assert user.valid?
10 end
11 end
こんな感じでtest作ってくれる。
とりあえずこのまま実行。
$ bundle exec rake test test/models/user_test.rb
Started
ERROR["test_valid", UserTest, 2015-11-16 20:02:17 +0900]
test_valid#UserTest (1447671737.22s)
ActiveRecord::StatementInvalid: ActiveRecord::StatementInvalid: Mysql2::Error: Field 'name' doesn't have a default value: INSERT INTO `users` (`created_at`, `updated_at`, `id`) VALUES ('2015-11-19 01:50:15', '2015-11-19 01:50:15', 980190962)
怒られる。
今回作ったテストケースではdoes'nt have a default value
って言われてるけど、実際にやってたときは「unique indexついてるけどuniqueじゃないよこれ」みたいなこと言われて困ってた。
原因
原因は単純な話で、一緒にcreateされてたtest/fixtures/users.yml
を見逃してたから。
text/fixtures/users.yml
1 # Read about fixtures at
2 # http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
3
4 # This model initially had no columns defined. If you add columns to the
5 # model remove the '{}' from the fixture names and add the columns immediately
6 # below each fixture, per the syntax in the comments below
7 #
8 one: {}
9 # column: value
10 #
11 two: {}
12 # column: value
中身が空のfixtureだー!これはダメ。
テストデータ作ろうとした時に引っかかったからMysqlに怒られてたのね。
FactoryGirl
を使ってるのでfixtureファイルを削除して解決。