我查看了堆栈溢出的答案,发现有些人发布了类似的问题,但解决方案没有帮助。从我可以告诉我的代码是完全正确的。为什么此规范不能按预期工作?
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 }
end
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
describe "when email address is already taken" do
before do
user_with_same_email = @user.dup
user_with_same_email.email = @user.email.upcase
user_with_same_email.save
end
#it "should not be valid" do
# expect(@user).not_to be_valid
#end
it { should_not be_valid }
end
end
最后的规范失败。
我的用户验证是这样:
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
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 }, uniqueness: { case_sensative: false }
end
我完全跟着教程,但我似乎无法得到这个验证才能正常工作。我知道这个教程有点老,我可能会使用一些新的宝石。我也知道这不是做这种验证的最好方法,但教程刚开始时非常简单。这里发生了什么?
谢谢!
编辑: 没有错误。验证失败时应该是成功的。
Failures:
1) User when email address is already taken should not be valid
Failure/Error: it { should_not be_valid }
expected #<User id: nil, name: "Example User", email: "[email protected]", created_at: nil, updated_at: nil> not to be valid
# ./spec/models/user_spec.rb:58:in `block (3 levels in <top (required)>'
Finished in 0.09887 seconds
1 example, 1 failure
再次编辑。 user_spec.rb已被完全粘贴在任务中。抱歉,我对于ruby真的很陌生,并没有意识到可能需要帮助解决问题。
你可以把错误信息? –
期望未能得到满足,还是因为异常引发而失败? –
你在哪里设置主题?换句话说,规范中的“它”是什么?请注意,有问题的电子邮件不是大写的,所以除非你有一个回调/ etc下层 - 它看起来像你测试错误的东西。用-b运行,然后调用save !. –