我有组和用户模型。用户属于组,组有很多用户。
我正在使用 Rspec 编写集成测试:当一个组至少有一个用户时,该组不会被删除。
工厂:
FactoryGirl.define do
factory :group_with_users do
name 'Demo group'
ignore do
users_count 2
end
after(:create) do |group, evaluator|
FactoryGirl.create_list(:user, evaluator.users_count, group: group)
end
end
end
规格:
require 'spec_helper'
feature 'admin can manage groups' do
background do
@group_spec = FactoryGirl.create(:group_with_users)
visit groups_path
end
scenario "don't delete group because it's not empty (there are users)" do
page.should have_text(@group_spec.name)
# DEBUGGING
binding.pry
click_link 'Delete'
page.should have_text('Not deleted')
page.should have_text(@group_spec.name)
end
end
组控制器:
def destroy
@group = Group.find(params[:id])
# DEBUGGING
binding.pry
msg = if @group.users.size > 1
'Not deleted'
else
@group.delete
'Deleted'
end
redirect_to groups_path, notice: msg
end
问题是该组正在被删除。所以我决定调试(参见规范和控制器中的#DEBUGGING)代码。
在规格中:
@group_spec.users.size
>> 2
但在控制器中:
@group.users.size
>> 0
比较两个对象:
@group === @group_spec
>> true
编辑: 在规范调试中:
Group.find(@group_spec._id).users.size
>> 0
PS:“数据模型”有点复杂。但这就是想法。