我在Rspec中收到外键约束错误,但在我的Users模型上测试我的销毁操作时却没有。
我没有级联,因为我希望已删除用户创建的对象保留在数据库中。相反,我已经编写了一个自定义方法来将属于被删除用户的任何对象重新分配给执行删除的用户。
我在测试中呼叫delete :destroy, id: @user
。
以下是我的控制器操作和防止外键约束的帮助程序。
def destroy
@user = User.find(params[:id])
@flash_message = String.new # this is used by the next method in case we do cleanup.
clean_up_before_delete
unless @user == current_user
@user.destroy
flash[:success] = 'User deleted.' + @flash_message
redirect_to users_url
else
flash[:danger] = "You can't delete yourself."
redirect_to users_url
end
end
def clean_up_before_delete
# this prevents us from having orphaned comments, histories and work_items
unless @user.work_items.blank?
@user.work_items.each do |w|
w.user_id = current_user.id
w.owned = false
w.save
end
@flash_message = ' Work items reassigned to queue.'
end
@comments = Comment.where(user_id: @user.id)
unless @comments.blank?
@comments.each do |c|
c.body += " (Original commenter #{@user.name} was deleted.)"
c.user_id = current_user.id
c.save
end
end
@histories = History.where(user_id: @user.id)
unless @histories.blank?
@histories.each do |h|
h.body += " (Original user #{@user.name} was deleted.)"
h.user_id = current_user.id
h.save
end
end
end
这是我收到的错误:
ActiveRecord::InvalidForeignKey: ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: update or delete on table "users" violates foreign key constraint "fk_rails_a9cab3453b" on table "work_items"
如果我在实际的网络浏览器中执行此操作,我能够删除用户而不会收到此错误 - 问题似乎只发生在Rspec中。我错过了什么吗?
以下是我认为的HAML:
- if !current_user?(user)
= link_to "Delete", user,
method: :delete,
data: { confirm: "Are you sure you want to delete #{user.name}?" },
class: "btn btn-xs btn-danger"