任何人都可以看到Rspec的错误吗?我对无效电子邮件的所有测试都失败了(即,它们应该是无效的,但不知何故在Rspec中),但在实际代码中,它工作正常,不允许任何坏的电子邮件。验证甚至可以在我的控制台中使用....
两个注释:
型号代码
validate :create_validation, on: :create
def create_validation
errors[:base] << "Please enter a valid email address to continue" if self.email.blank? || (( /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i =~ self.email) == nil)
end
#The RegEx is from Michael Hartl's tutorial
规范代码
describe Signup do
before do
@signup = FactoryGirl.create(:signup)
end
subject { @signup }
describe "email tests" do
describe "invalid tests" do
# blank email
before { @signup.email = " " }
it { should_not be_valid }
# invalid format email
addresses = %w[user@foo..com, user@foo,com user_at_foo.org example.user@foo. foo@bar_baz.com foo@bar+baz.com]
addresses.each do |invalid_address|
before { @signup.email = invalid_address }
it { should_not be_valid }
end
end
end
end
规范助手中的工厂女孩代码
FactoryGirl.define do
factory :signup do |f|
f.email { Faker::Internet.email }
#... other attributes
end
端
答案 0 :(得分:1)
据我所知,您只在创建时验证代码!但是在测试中你在块之前创建了对象并且它在测试中持久存在 - 因此跳过了验证。
尝试此变体
describe Signup do
before do
@signup = FactoryGirl.build(:signup)
end
subject { @signup }
describe "email tests" do
describe "invalid tests" do
# blank email
before { @signup.email = " " }
it { should_not be_valid }
# invalid format email
addresses = %w[user@foo..com, user@foo,com user_at_foo.org example.user@foo. foo@bar_baz.com foo@bar+baz.com]
addresses.each do |invalid_address|
before { @signup.email = invalid_address }
it { should_not be_valid }
end
end
end
end
我希望验证会在已建成但未保存的记录中触发。
PS或者你可以删除选项on: :create