Rails 3验证 - 关联属性,RSpec和工厂女孩

时间:2011-05-13 03:09:15

标签: ruby-on-rails ruby-on-rails-3 rspec factory-bot autotest

我正在尝试在rails 3中编写一个验证类,它将检查是否存在至少一个具有特定属性值的关联对象。

在我的方案中,帐户可以有很多用户。 User模型具有“Role”字符串字段。帐户必须至少有一个角色等于“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

我的假设是,我跳到了某个地方持续存在的物体,但我不知道在哪里。感谢您的帮助/指导!

0 个答案:

没有答案