product_test.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. require 'test_helper'
  10. class ProductTest < ActiveSupport::TestCase
  11. test "product attributes must not be empty" do
  12. product = Product.new
  13. assert product.invalid?
  14. assert product.errors[:title].any?
  15. assert product.errors[:description].any?
  16. assert product.errors[:price].any?
  17. assert product.errors[:image_url].any?
  18. end
  19. test "product price must be positive" do
  20. product = Product.new(title: "My Book Title",
  21. description: "yyy",
  22. image_url: "zzz.jpg")
  23. product.price = -1
  24. assert product.invalid?
  25. assert_equal "must be greater than or equal to 0.01",
  26. product.errors[:price].join('; ')
  27. product.price = 0
  28. assert product.invalid?
  29. assert_equal "must be greater than or equal to 0.01",
  30. product.errors[:price].join('; ')
  31. product.price = 1
  32. assert product.valid?
  33. end
  34. def new_product(image_url)
  35. Product.new(title: "My Book Title",
  36. description: "yyy",
  37. price: 1,
  38. image_url: image_url)
  39. end
  40. test "image url" do
  41. ok = %w{ fred.gif fred.jpg fred.png FRED.JPG FRED.Jpg
  42. http://a.b.c/x/y/z/fred.gif }
  43. bad = %w{ fred.doc fred.gif/more fred.gif.more }
  44. ok.each do |name|
  45. assert new_product(name).valid?, "#{name} shouldn't be invalid"
  46. end
  47. bad.each do |name|
  48. assert new_product(name).invalid?, "#{name} shouldn't be valid"
  49. end
  50. end
  51. test "product is not valid without a unique title" do
  52. product = Product.new(title: products(:ruby).title,
  53. description: "yyy",
  54. price: 1,
  55. image_url: "fred.gif")
  56. assert !product.save
  57. assert_equal "has already been taken", product.errors[:title].join('; ')
  58. end
  59. test "product is not valid without a unique title - i18n" do
  60. product = Product.new(title: products(:ruby).title,
  61. description: "yyy",
  62. price: 1,
  63. image_url: "fred.gif")
  64. assert !product.save
  65. assert_equal I18n.translate('activerecord.errors.messages.taken'),
  66. product.errors[:title].join('; ')
  67. end
  68. end