require 'test_helper' class ProductTest < ActiveSupport::TestCase # Rails is already doing this! (convention over configuration!) fixtures :products # test "the truth" do # assert true # end test "product attributes must not be empty" do product = Product.new assert product.invalid? assert product.errors[:title].any? assert product.errors[:description].any? assert product.errors[:image_url].any? assert product.errors[:price].any? end test "product price be positive" do product = Product.new(title: 'My Book Title', description: 'My Description.', image_url: 'image.jpg') product.price = -1 assert product.invalid? assert_equal ['must be greater than or equal to 0.01'], product.errors[:price] product.price = 0 assert product.invalid? assert_equal ['must be greater than or equal to 0.01'], product.errors[:price] product.price = 1 assert product.valid? end def new_product(image_url) product = Product.new(title: 'My Book Title', description: 'My Description.', image_url: image_url, price: 1) end test "image url" do ok = %w{ fred.jpg hans.png paul.Png peter.JPG http://a.b.c.d/images/foo.gif } bad =%w{ fred.doc hans.gif/more } ok.each { |name| assert new_product(name).valid? "#{name} shouldn't be invalid" } bad.each do |name| assert new_product(name).invalid? "#{name} shouldn't be valid" end end test "product is not valid without a unique title - i18n" do product = Product.new(title: products(:ruby).title, description: 'Foo.', price: 1, image_url: "foo.jpg") assert product.invalid? assert_equal [I18n.translate('errors.messages.taken')], product.errors[:title] end test "product is not valid without minimum 5 characters in title" do product = Product.new(title: 'Shrt', description: 'A short work.', price: 0.99, image_url: 'short.jpg') assert product.invalid? assert_equal ['is too short (minimum is 5 characters)'], product.errors[:title] end end