我正在按照文档中的说明进行操作,但仍然出现验证错误:
验证失败:电子邮件已被占用
FactoryGirl.define do
sequence :email do |n|
"test#{n}@factory.com"
end
factory :user do
email
password '12345678'
password_confirmation '12345678'
goal_id 1
experience_level_id 1
gender 'Female'
end
end
有人知道我在这里做错了什么吗?
编辑:
这是失败的规范。如果您取消注释主题块并注释掉 FactoryGirl 内容,它工作正常。我正在尝试改用 FactoryGirl。
require 'spec_helper'
require 'cancan/matchers'
describe User do
# subject(:user) do
# Program.create!(name: 'test', gender: 'Female', goal_id: '1', experience_id: '1')
# User.create!(email: 'test@test.com', password: '12345678', password_confirmation: '12345678', goal_id: '1', experience_level_id: '1', gender: 'Female')
# end
FactoryGirl.create(:program)
puts FactoryGirl.create(:user).inspect
it "should be assigned a program when it's created" do
user.programs.should exist
end
it "should be valid with a name, goal, password, password_confirmation, experience_level, and gender" do
user.should be_valid
end
it { should respond_to(:programs) }
its('programs.last.name') {should == 'Test'}
it "should be assigned imperial as the default measurement_units" do
user.measurement_units.should eq("imperial")
end
it 'validates presence of gender, goal_id, and experience_level_id' do
user = User.new(gender: nil)
user.should validate_presence_of(:gender)
user.should validate_presence_of(:goal_id)
user.should validate_presence_of(:experience_level_id)
end
end
编辑2:
我已经按照答案之一的建议更新了我的规范,所以现在我的规范运行了,但是我得到一个失败的测试并出现验证错误。这是更新的代码:
describe User do
subject(:user) do
# Program.create!(name: 'test', gender: 'Female', goal_id: '1', experience_id: '1')
# User.create!(email: 'test@test.com', password: '12345678', password_confirmation: '12345678', goal_id: '1', experience_level_id: '1', gender: 'Female')
FactoryGirl.create(:program)
FactoryGirl.create(:user)
end
it "should be assigned a program when it's created" do
user.programs.should exist
end
来自失败测试的消息:
Failures:
1) User should be assigned a program when it's created
Failure/Error: FactoryGirl.create(:user)
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken
# ./spec/models/user_spec.rb:9:in `block (2 levels) in <top (required)>'
# ./spec/models/user_spec.rb:13:in `block (2 levels) in <top (required)>'
有任何想法吗?