Ruby on Rails - 正则表达式电子邮件验证不起作用

时间:2017-07-29 03:48:11

标签: ruby-on-rails

我正在尝试在第6章中使用Michael Hartl的rails教程书中的正则表达式电子邮件验证示例,但由于某种原因,测试“电子邮件验证应该接受有效地址”在有效的电子邮件地址上失败。我按照建议使用Rubular尝试了正则表达式并将其传递到那里。如果有人知道为什么它在我的rails代码中失败了,我会很感激帮助搞清楚它。感谢。

测试失败

test "email validation should accept valid addresses" do
    valid_addresses = %w[user@example.com USER@foo.COM first.last@foo.jp]
    valid_addresses.each do |valid_address|
        @user.email = valid_addresses
        assert @user.valid?, "#{valid_address.inspect} should be valid"
    end
end

具有正则表达式和验证定义的用户类

class User < ActiveRecord::Base

    has_many :posts, dependent: :destroy
    has_many :text_posts, dependent: :destroy
    has_many :image_posts, dependent: :destroy

    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}

end

1 个答案:

答案 0 :(得分:1)

目前,您正在将用户电子邮件设置为所有有效电子邮件的数组,而不仅仅是当前的电子邮件:

@user.email = valid_addresses

应该是

@user.email = valid_address