我正在关注RoR教程;我坚持使用电子邮件格式验证部分。我用书中的代码检查了三次,没有遗漏或错误,但我收到了这个错误:
$ bundle exec rspec spec/models/user_spec.rb
...[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
....F
Failures:
1) User when name is not present when email format is valid should be valid
Failure/Error: expect(@user).to be_valid
expected #<User id: nil, name: " ", email: "user@foo.COM", created_at: nil, updated_at: nil> to be valid, but got errors: Name can't be blank
# ./spec/models/user_spec.rb:37:in `block (5 levels) in <top (required)>'
# ./spec/models/user_spec.rb:35:in `each'
# ./spec/models/user_spec.rb:35:in `block (4 levels) in <top (required)>'
Finished in 0.07755 seconds
8 examples, 1 failure
Failed examples:
rspec ./spec/models/user_spec.rb:33 # User when name is not present when email format is valid should be valid
spec / models / user_spec.rb文件:
require 'spec_helper'
describe User do
before { @user = User.new(name: "Example User", email: "user@example.com") }
subject { @user }
it { should respond_to(:name) }
it { should respond_to(:email) }
it { should be_valid }
describe "when name is not present" do
before { @user.name = " " }
it { should_not be_valid }
describe "when email is not present" do
before { @user.email = " " }
it { should_not be_valid }
end
describe "when name is too long" do
before { @user.name = "a" * 51 }
it { should_not be_valid }
end
describe "when email format is invalid" do
it "should be invalid" do
addresses = %w[user@foo,com user_at_foo.org example.user@foo.
foo@bar_baz.com foo@bar+baz.com]
addresses.each do |invalid_address|
@user.email = invalid_address
expect(@user).not_to be_valid
end
end
end
describe "when email format is valid" do
it "should be valid" do
addresses = %w[user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp a+b@baz.cn]
addresses.each do |valid_address|
@user.email = valid_address
expect(@user).to be_valid
end
end
end
end
end
app / models / user.rb文件:
class User < ActiveRecord::Base
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }
end
答案 0 :(得分:1)
需要设置名称才能使其有效。
看看你写的规范:
describe "when name is not present" do
before { @user.name = " " }
it { should_not be_valid }
end
因此,如果您希望通过电子邮件测试,则需要确保事先设置名称。