第7章「タスクB:検証とユニットテスト」
こんばんは。 今日は昨日に引き続き、本の第7章を進めていました。 というか進められませんでした。
モデルのユニットテスト
まずは「depot/app/models/product.rb」から
class Product < ActiveRecord::Base # Title, Description, Image_urlが空でないことを検証 validates :title, :description, :image_url, presence: true # Priceが1以上であることを確認(Priceには小数点以下2桁しか保存されないため) validates :price, numericality: {greater_than_or_equel_to: 0.01} # 名称の重複がないか確認 validates :title, uniqueness: true # Image_urlがgif,jpg,pngであるか確認 validates :image_url, allow_blank: true, format: { with: %r{\.(gif|jpg|png)\z}i, message: 'はGIF,JPG,PNG画像のURLでなければなりません' } end
「depot/app/controllers/products_controller.rb」もちょこちょこ変更してさぁユニットテストだ!と軽快にスタートしました。 しかし、「depot/test/models/product.rb」をいじってる最中でした。
test "product price must be positive" do product = Product.new(title: "My Book Title", description: "yyy", image_url: "zzz.jpg") product.price = -1 # ここが10行目 assert product.invalid? assert_equal "must be greater than or equal to 0.01", product.errors[:price].join('; ') product.price = 0 assert product.invalid? assert_equal "must be greater than or equal to 0.01", product.errors[:price].join('; ') product.price = 1 assert product.valid? end
で
rake test:units
を実行すると…
Run options: --seed 12156 # Running: F Finished in 0.034827s, 28.7134 runs/s, 28.7134 assertions/s. 1) Failure: ProductTest#test_product_price_must_be_positive [.../depot/test/models/product_test.rb:10]: Failed assertion, no message given. 1 runs, 1 assertions, 1 failures, 0 errors, 0 skips
これだけ通らない。本来なら「3 assertions」になるはずなんですがね… おんなじような悩みを抱えている人もいるみたいですが、解決方法がよく分かってない。
Rails, Failed assertion, no message given - Stack Overflow
なんかずっと悩んで調べていたのですが、小手先のコード変更だけではどうしようもならなかったです。 あとの「ImageのURLテスト」や「フィックスチャデータの使用」では普通に通った。 ということはPriceに問題あるのかなーと思ったのですが、どうなんでしょうかね。 この部分を飛ばせばひとまずこの章はクリアしました。
まだまだ先は長い。