zzyclark
zzyclark

Reputation: 161

Rails model validation works, but rake test fail

Currently, i'm learning rails. When i build a model with validation format:

class Product < ActiveRecord::Base
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: 'must be a URL for GIF, JPG or PNG image.',
    multiline: true
} end

this validation is to test whether the image_url has an extension with gif, jpg or png.

When i run the server and test by myself, everything work fine. While when i try to build the model test, test not pass.

enter require 'test_helper'     

class ProductTest < ActiveSupport::TestCase                                                                            

def new_product(image_url)
    Product.new(title: "bool",
            description: "daf",
            image_url: image_url)
end

test "image url" do
    ok = %w{fred.gif fred.jpg fred.png RED.JPG RED.Jpg http://a.b.c/x/y/z/fesd.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 
end

It also through me that 1 assert is failure:

1) Failure:
ProductTest#test_image_url [/home/clark/Desktop/Agile_Rails/depot/test/models/product_test.rb 38]:
fred.gif shouldn't be invalid

Can anybody help me, is my testing code wrong?

Upvotes: 0

Views: 166

Answers (1)

edariedl
edariedl

Reputation: 3352

I don't know if you found it yet but problem is not in the image_url. You are validating also price for numericality but you are letting it blank in your test so product is invalid because of price field.

Upvotes: 2

Related Questions