我的ruby RSpec Code失败了。 我希望你能帮助我。 当我添加电子邮件重复验证时,失败即将到来。
这是我的user_spec代码
require 'spec_helper'
describe User do
before do
@user = User.new(name: "Example User", email: "user@example.com")
end
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[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
@user.should_not 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
@user.should 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 }
end
end
这是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 }, uniqueness: { case_sensitive: false }
end
我在测试时失败了。我不知道什么是错的,我也没有在网上找到解决方案。
$ bundle exec rspec spec/models/user_spec.rb
Your Gemfile lists the gem rspec-rails (>= 0) more than once.
You should probably keep only one of them.
While it's not a problem now, it could cause errors if you change the version of just one of them later.
..[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
Failure/Error: it { should be_valid }
expected valid? to return true, got false
# ./spec/models/user_spec.rb:14:in `block (2 levels) in <top (required)>'
Finished in 0.26438 seconds
9 examples, 1 failure
Failed examples:
rspec ./spec/models/user_spec.rb:14 # User
答案 0 :(得分:0)
我尝试了你的代码,但一切都变成了绿色。
我的猜测是你在早期的rspec运行中遇到了一些异常,因此你的测试数据库中有一些数据从未被成功删除过。
尝试
rake db:test:prepare
看看你是否还有问题。
答案 1 :(得分:0)
这更多是通过进一步的故障排除建议而非实际答案。
接下来要查找的关键信息是哪个验证失败。在IRB控制台会话中尝试运行
user = User.new(name: "Example User", email: "user@example.com")
user.valid? # we're expecting this to return false
user.errors.messages # returns the message for the validation that's failing.
如果您知道哪些验证失败,那么缩小问题的范围就会轻松得多。