我遵循RoR教程;我堅持在電子郵件格式驗證部分。我的代碼檢查三次從書中,沒有任何遺漏或錯誤,但我得到這個錯誤:帶電子郵件格式驗證失敗的rspec測試
$ 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: "[email protected]", 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
規格/型號/ user_spec.rb文件:
require 'spec_helper'
describe User do
before { @user = User.new(name: "Example User", email: "[email protected]") }
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[[email protected],com user_at_foo.org [email protected]
[email protected]_baz.com [email protected]+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[[email protected] [email protected] [email protected] [email protected]]
addresses.each do |valid_address|
@user.email = valid_address
expect(@user).to be_valid
end
end
end
end
end
應用程序/模型/user.rb文件:
class User < ActiveRecord::Base
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }
end
您的縮進遍佈各處,導致您將所有內容都嵌入「當名稱不存在」塊 – 2014-09-03 17:20:00