💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 6.5 练习 电子书中有练习的答案,如果想阅读参考答案,请[购买电子书](http://railstutorial-china.org/#purchase)。 避免练习和正文冲突的方法参见[3.6 节](chapter3.html#mostly-static-pages-exercises)中的说明。 1. 为[代码清单 6.31](#listing-email-downcase) 中把电子邮件地址转换成小写字母形式的代码编写一个测试,如[代码清单 6.41](#listing-email-downcase-test) 所示。这段测试使用 `reload` 方法从数据库中重新加载数据;使用 `assert_equal` 方法测试是否相等。为了验证[代码清单 6.41](#listing-email-downcase-test) 是正确的,先把 `before_save` 那行注释掉,看测试是否失败,然后去掉注释,看测试能否通过。 2. 在 `before_save` 回调中使用 `email.downcase!` 直接修改 `email` 属性的值([代码清单 6.42](#listing-downcase-bang)),运行测试组件,确认可以这么做。 3. 我们在 [6.2.4 节](#format-validation)说过,[代码清单 6.21](#listing-validates-format-of-email) 中的电子邮件地址正则表达式能匹配出现连续点号的无效地址,例如 _foo@bar..com_。把这个地址添加到[代码清单 6.19](#listing-email-format-validation-tests) 中的无效地址列表中,让测试失败,然后使用[代码清单 6.43](#listing-better-email-regex) 中较复杂的正则表达式让测试通过。 ##### 代码清单 6.41:[代码清单 6.31](#listing-email-downcase) 中把电子邮件地址转换成小写形式的测试 test/models/user_test.rb ``` require 'test_helper' class UserTest < ActiveSupport::TestCase def setup @user = User.new(name: "Example User", email: "user@example.com", password: "foobar", password_confirmation: "foobar") end . . . test "email addresses should be unique" do duplicate_user = @user.dup duplicate_user.email = @user.email.upcase @user.save assert_not duplicate_user.valid? end test "email addresses should be saved as lower-case" do mixed_case_email = "Foo@ExAMPle.CoM" @user.email = mixed_case_email @user.save assert_equal mixed_case_email.downcase, @user.reload.email end test "password should have a minimum length" do @user.password = @user.password_confirmation = "a" * 5 assert_not @user.valid? end end ``` ##### 代码清单 6.42:`before_save` 回调的另一种实现方式 GREEN app/models/user.rb ``` class User < ActiveRecord::Base before_save { email.downcase! } validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } has_secure_password validates :password, presence: true, length: { minimum: 6 } end ``` ##### 代码清单 6.43:不允许电子邮件地址中有多个点号的正则表达式 GREEN app/models/user.rb ``` class User < ActiveRecord::Base before_save { email.downcase! } validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } has_secure_password validates :password, presence: true, length: { minimum: 6 } end ```