Foreign key constraint violation in tests but not in practice
<p>I'm receiving a foreign key constraint error in Rspec but not in practice when testing my destroy action on my Users model.</p>

<p>I'm not cascading since I want objects created by deleted users to remain in the database. Instead, I've written a custom method to reassign any objects that belong to the user being deleted to the user performing the deletion.</p>

<p>I'm calling <code>delete :destroy, id: @user</code> in my tests.</p>

<p>The following is my controller action and the helper to prevent foreign key constraints.</p>

<pre><code>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
</code></pre>

<p>And here is the error I am receiving:
<code>ActiveRecord::InvalidForeignKey:         ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  update or delete on table "users" violates foreign key constraint "fk_rails_a9cab3453b" on table "work_items"</code></p>

<p>I'm able to delete users without receiving this error if I do it in an actual web browser - the problem only seems to happen in Rspec. Am I missing something?</p>

<p>Here is the HAML in my view:</p>

<pre><code>- 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"      
</code></pre>