我正在测试我的用户模型并研究 FactoryGirl 的工作原理。当我在我的user_spec.rb中执行此操作时:
before(:each) do
@user = User.new(username: 'ExampleUser', email: 'user@example.com', timezone: 'Eastern Time (US & Canada)', password: 'example')
end
一切都会过去,但如果我这样做:
before(:each) do
@user = FactoryGirl.create(:user)
end
它未能通过测试来查看用户的用户名和电子邮件是否已被使用。
1) User when username is already taken
Failure/Error: it { should_not be_valid }
expected valid? to return false, got true
# ./spec/models/user_spec.rb:151:in `block (3 levels) in <top (required)>'
2) User when email address is already taken
Failure/Error: it { should_not be_valid }
expected valid? to return false, got true
# ./spec/models/user_spec.rb:142:in `block (3 levels) in <top (required)>'
Finished in 1.8 seconds
29 examples, 2 failures
这些是测试:
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
describe 'when username is already taken' do
before do
user_with_same_username = @user.dup
user_with_same_username.username = @user.username.upcase
user_with_same_username.save
end
it { should_not be_valid }
end
有人可以解释吗?我认为 FactoryGirl 应该让我像使用它一样使用它User.new
,这是我的第一个有效示例。