我正在尝试在 rails 3 中编写一个验证类,它将检查是否存在至少一个具有特定属性值的关联对象。
在我的场景中,一个帐户可以有很多用户。用户模型有一个“角色”字符串字段。一个帐户必须至少有一个角色等于“admin”的用户。
以下代码在我的测试期间被破坏(我正在使用 rspec & Factory Girl)。执行测试时,account_id 返回为 null。
这是模型:
class Account < ActiveRecord::Base
validates :name, :presence => true, :uniqueness => true
validate :has_one_admin
has_many :users
attr_accessible :name
private
def has_one_admin
User.where(:role => "admin", :account_id => self.id).count > 0
end
end
这是 rspec 引发的错误:
Error message being thrown: Failure/Error: @account = Factory(:account_with_admin)
ActiveRecord::StatementInvalid:
SQLite3::SQLException: no such column: users.account_id: SELECT COUNT(*) FROM "users" WHERE "users"."role" = 'admin' AND "users"."account_id" IS NULL
这是 RSpec 测试:
require 'spec_helper'
describe Team do
# - Removed -
# before(:each) do
# @account = Factory(:account)
# @attr = { :name => "Testing Team"}
# end
# Modified after discussion...
before(:each) do
@user = Factory(:user)
@act_attr = { :name => "My Account",
:users => @user }
@account = Account.new(@act_attr)
@attr = { :name => "Testing Team"}
end
# End of modification
it "must have a name" do
no_name_team = Team.new(@attr.merge(:name => ""))
no_name_team.should_not be_valid
end ...
最后,我的工厂文件:
Factory.define :admin, :class => User do |f|
f.email 'admin@admin.com'
f.password 'password'
f.role 'admin'
end
Factory.define :team, :class => Team do |f|
f.name 'Testing Team'
end
Factory.define :account, :class => Account do |f|
f.name 'Testing Account'
end
Factory.define :account_with_admin, :parent => :account do |f|
f.after_create { |a| Factory(:admin, :account => a) }
end
我的假设是我在某个地方的对象持续存在之前跳跃,但我只是不确定在哪里。感谢您的帮助/指导!