我有 2 个模型,User
和 Bucket
. User
has_many
Buckets
和 Bucket
belongs_to
一个 User
.
在 factories.rb
, 我有:
Factory.define :user do |user|
user.email "teste@test.com"
user.password "foobar"
user.password_confirmation "foobar"
end
Factory.sequence :email do |n|
"person-#{n}@example.com"
end
Factory.define :bucket do |bucket|
bucket.email "user@example.com"
bucket.confirmation false
bucket.association :user
end
我有一个 login_user 模块,如下所示:
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
@user = Factory.create(:user)
#@user.confirm!
sign_in @user
end
end
我正在使用 Spork 和 Watch 以及我的
Buckets_controller_spec.rb
很简单:describe "User authenticated: " do
login_user
@bucket = Factory(:bucket)
it "should get index" do
get 'index'
response.should be_success
end
...
end
错误总是一样的:
Failures:
1) BucketsController User authenticated: should get index
Failure/Error: Unable to find matching line from backtrace
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken
# ./lib/controller_macros.rb:12:in `block in login_user'
只有当我拥有
Factory(:bucket)
时才会发生这种情况.当我不添加 Factory(:bucket)
时,登录工作正常.它总是同样的错误。我已尝试添加
:email => Factory.next(:email)
给用户,但没有成功。编辑:
在
rails c test
:ruby-1.9.2-p180 :019 > bucket = Factory(:bucket, :email => "hello@hello.com")
ActiveRecord::RecordInvalid: Validation failed: Email has already been taken
ruby-1.9.2-p180 :018 > Bucket.create(:email => "hello@hello.com")
=> #<Bucket id: 2, email: "hello@hello.com", confirmation: nil, created_at: "2011-04-08 21:59:12", updated_at: "2011-04-08 21:59:12", user_id: nil>
编辑2:
我发现错误在关联中,但是,我不知道如何解决它。
bucket.association :user
最佳答案
当您使用关联定义工厂时,您需要为工厂提供一个对象,以便在您使用工厂时与之关联。
这应该有效:
describe "User authenticated: " do
login_user
@bucket = Factory(:bucket, :user => @user)
it "should get index" do
get 'index'
response.should be_success
end
end
这样,factorygirl 就知道要制作一个与@user 关联的存储桶。
关于ruby-on-rails-3 - 导轨 3 + Rspec 2 : Validation failed: Email has already been taken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5601163/