rake test が fail その1
RailsによるアジャイルWebアプリケーション開発 第4版にて、
何故かテストが通らないという原因不明事件が自分の中で発生してます。
「7.2 モデルのユニットテスト」の
product price must be positive と image url が正しい値なのにvalid?でfalesが返るという・・・
まぁ、こんな感じで
ProductTest test_image_url FAIL fred.jpg shouldn't be invalid Assertion at /Users/shiori/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.1.3/lib/active_support/testing/setup_and_teardown.rb:35:in `block in run' test_product_attributes_must_not_be_empty PASS test_product_is_not_valid_without_a_unique_tilte PASS test_product_is_not_valid_without_a_unique_tilte_-_l18n PASS test_product_price_must_be_positive FAIL Failed assertion, no message given. Assertion at /Users/shiori/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.1.3/lib/active_support/testing/setup_and_teardown.rb:35:in `block in run'
で、テスト部分はどうなっているかというと
test "product price must be positive" do product = Product.new(title: "My Book Title", description: "yyy", image_url: "zzz.jpg") product.price = -1 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 def new_product(image_url) Product.new(title: "my book title", description: "yyy", price: 1, image_url: "#{image_url}") end test "image url" do ok = %w{fred.jpg fred.png RFED.JPG FRED.Jpg http://a.b.c/x/y/z/fred.gif} bad = %w{ fred.doc fred.gif/more fred.gif.more} ok.each do |name| assert new_product(name).valid?, "#{name} shouldn't be invalid" end bad.each do |name| assert new_product(name).invalid?, "#{name} shouldn't be valid" end end
モデルは次のとおりです。
# encoding: utf-8 class Product < ActiveRecord::Base has_many :line_items has_many :orders, through: :line_items before_destroy :ensure_not_referenced_by_any_line_item validates :title, :description, :image_url, presence: true validates :price, numericality: {greater_than_or_equal_to: 0.01} validates :title, uniqueness: true validates :image_url, allow_blank: true, format: { with: %r{\.(gif|jpg|png)$}i, message: 'はGIF,JPG,PNG画像のURLでなければなりません' } validates :description, length: { minimum: 10, message: 'は10文字以上でなければなりません' } private # この商品を参照している品目がないことを確認する def ensure_not_referenced_by_any_line_item if line_items.empty? return true else errors.add(:base, '品目が存在します') return false end end end
テキスト通りにやっているはずなのだが、何故か通らない。
valid?の部分をinvalid?にすると通るんだが・・・いや、おかしいだろ!
アプリではjpgやpngでエラーがでることなくデータベースに登録できました。
もちろん、拡張子がjpg/png/gif以外ならエラーを返します。
値段でもおなじです。
う〜ん、なんでだ??
** 追記 **
解決しました。
validates :description, length: { minimum: 10, message: 'は10文字以上でなければなりません' }
で、descriptin のサイズを10文字以上としているのに、テストで作成しているデータが10文字以下だったという・・・凡ミスです。
あー、自分のあほーぅ