我有 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