Ruby on Rails - 访问数据:has_many => :通过协会

时间:2010-01-17 15:05:11

标签: ruby-on-rails testing associations

我正试图在Rails中掌握这种类型的关联

我有以下三种模式:

User

has_many: 'memberships'
has_many: groups, :through => 'memberships'

Membership

belongs_to: 'user'
belongs_to 'group'

Group

has_many: 'memberships'
has_many: 'users', :through => 'memberships'

我有一个before_create方法,可以将新用户添加到默认用户组。

user.rb

  attr_accessor :group_ids

  before_create :add_user_to_default_group
  after_save :update_groups

  def add_user_to_default_group
      self.group_ids = [1]
  end



 #after_save callback to handle group_ids
  def update_groups
    unless group_ids.nil?
      self.memberships.each do |m|
        m.destroy unless group_ids.include?(m.group_id.to_s)
        group_ids.delete(m.group_id.to_s)
      end 
      group_ids.each do |g|
        self.memberships.create(:group_id => g) unless g.blank?
      end
      reload
      self.group_ids = nil
    end
  end

我正在尝试编写测试以确保正确发生这种情况。

user = User.new
user.username = 'testuser'
user.email = 'testuser@testdomain.co.uk'
user.password = 'testpass'
user.password_confirmation = 'testpass'
assert user.save
assert user.errors.empty?
assert !user.memberships.empty?

如果我使用user.memberships.empty,则测试通过,但如果我使用user.groups.empty?则不通过。我的印象是我应该可以通过.groups访问这些组?

我如何测试用户属于名为“活跃用户”的默认组?

任何建议都将不胜感激。

由于

1 个答案:

答案 0 :(得分:1)

您可能会使默认组过于复杂。这就是我想出来的。用户和组在我的示例中只有一个名称属性,以保持简单。

# app/models/user.rb
class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, :through => :memberships

  before_create :add_default_group

  protected

  def add_default_group
    self.groups << Group.find_by_name('Active Users')
  end
end

# app/models/group.rb 
class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships
end

# app/models/membership.rb 
class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

您只需要一次回调,before_create. And now for the test:

# test/unit/user_test.rb 
require 'test_helper'

class UserTest < ActiveSupport::TestCase
  def test_user_gets_default_group
    group = Group.create(:name => 'Active Users')
    user = User.new(:name => 'Test')

    assert user.save
    assert_equal [group], user.groups
  end
end

此测试不只是检查用户是否有某些组,而是检查您所期望的确切组,这是一个更严格的检查。