dimanche 24 avril 2016

rspec controller testing: "expected #count to have changed by -1, but was changed by 0"

am having trouble resolving this error. I'm not sure which part of the controller_spec is written wrongly. Please help!

Routes

Rails.application.routes.draw do
  resources :cases, only: [:index, :show, :new, :create, :edit, :update] do
    resources :links, only: [:create, :destroy]
  end
end

Controller

class LinksController < ApplicationController

  before_action :prepare_case

  def destroy
    @link = @case_file.links.find(params[:id])
    @link.destroy
    redirect_to case_path(@case_file)
  end

  private

  def prepare_case
    @case_file = CaseFile.find(params[:case_id])
  end
end

spec/factories

FactoryGirl.define do

  factory :link do

    case_file
    url 'www.google.com'

    trait :invalid do
      case_file nil
      url ''
    end
  end
end

spec/controllers

require 'rails_helper'

RSpec.describe LinksController, type: :controller do

  let(:user) { build(:user) }
  before { login_user user }
  #for user log in

  let(:case_file) { create(:case_file) }
  let(:link) { create(:link, case_file: case_file) }

  describe "DELETE destroy" do
    it "deletes a link" do
      expect { delete :destroy, id: link.id , case_id: case_file }.
      to change(Link, :count).by(-1) 
      expect(response).to redirect_to(case_path(case_file))
    end
  end
end

Error Message

$ rspec spec/controllers/links_controller_spec.rb ...F

Failures:

1) LinksController DELETE destroy deletes a link Failure/Error: expect { delete :destroy, id: link.id , case_id: case_file }. to change(Link, :count).by(-1)

expected #count to have changed by -1, but was changed by 0 # ./spec/controllers/links_controller_spec.rb:28:in `block (3 levels) in '

Finished in 1.18 seconds (files took 5.03 seconds to load) 4 examples, 1 failure

Failed examples:

rspec ./spec/controllers/links_controller_spec.rb:27 # LinksController DELETE destroy deletes a link

Aucun commentaire:

Enregistrer un commentaire