我有以下复杂的方法。我正在尝试寻找并实施可能的改进。现在我把最后一个 if 语句移到了Access
课堂上。
def add_access(access)
if access.instance_of?(Access)
up = UserAccess.find(:first, :conditions => ['user_id = ? AND access_id = ?', self.id, access.id])
if !up && company
users = company.users.map{|u| u.id unless u.blank?}.compact
num_p = UserAccess.count(:conditions => ['user_id IN (?) AND access_id = ?', users, access.id])
if num_p < access.limit
UserAccess.create(:user => self, :access => access)
else
return "You have exceeded the maximum number of alotted permissions"
end
end
end
end
我想在重构之前添加规范。我加了第一个。应该怎么像别人?
describe "#add_permission" do
before do
@permission = create(:permission)
@user = create(:user)
end
it "allow create UserPermission" do
expect {
@user.add_permission(@permission)
}.to change {
UserPermission.count
}.by(1)
end
end