Rails 4 พร้อม Devise ทดสอบคอนโทรลเลอร์ด้วย Rspec

ฉันยังใหม่กับการทดสอบ RSpec และกำลังพยายามเพิ่มการทดสอบไปยังคอนโทรลเลอร์ที่มีอยู่สำหรับแอป Rails 4 นี่คือลิงก์แอป Github ในกรณีที่คุณต้องการรายละเอียดเพิ่มเติม: https://github.com/iacobson/Zero2Dev

resources_controller.rb

    class ResourcesController < ApplicationController
        before_action :authenticate_user!, only:[:new, :create, :destroy]

          def destroy
            @resource = current_user.resources.find(params[:id])
            @resource.destroy
            redirect_to resources_path
          end

        private

        def resource_params
          params.require(:resource).permit(:content, :user_id) 
        end
    end

resources_controller_spec.rb

require 'rails_helper'

RSpec.describe ResourcesController, type: :controller do


  describe "DELETE #destroy" do
    let(:user1) {User.create!(name:"John", email:"[email protected]", password:"password")}
    let(:user2) {User.create!(name:"Mary", email:"[email protected]", password:"password")}
    let(:resource){user1.resources.create!(content: "Neque porro quisquam est qui dolorem ipsum")}


    it "deletes resource when user 1 (that created the resource) is logged-in" do
      sign_in user1
      delete :destroy, id: resource.id
      puts resource.content
      expect(resource.content).to be_nil
    end    
  end        
end

แต่ดูเหมือนว่า "ทรัพยากร" จะไม่ถูกลบ:

 Failure/Error: expect(resource.content).to be_nil
       expected: nil
            got: "Neque porro quisquam est qui dolorem ipsum"

ฉันลองใช้ตัวเลือกอื่นมากมายจากบทช่วยสอน Devise หรือจากบทช่วยสอนหรือคำตอบอื่น ๆ ที่ฉันพบบนอินเทอร์เน็ต แต่ทั้งหมดจบลงด้วยข้อผิดพลาด ฉันยังพยายามกำจัดการตรวจสอบ current_user ออกจากคอนโทรลเลอร์ด้วยซ้ำ แต่ก็ไม่มีโอกาส

วิธีที่ถูกต้องในการทดสอบการกระทำ Destroy ในคอนโทรลเลอร์โดยใช้ Rails4, Devise และ Rspec คืออะไร

ขอบคุณ !


person iacobSon    schedule 07.05.2015    source แหล่งที่มา


คำตอบ (1)


resource ที่คุณมีในข้อมูลจำเพาะของคุณถูกโหลดแล้ว และไม่เปลี่ยนแปลงเมื่อแถวถูกลบออกจากฐานข้อมูล คุณสามารถทำสองสิ่ง:

ทดสอบว่าทรัพยากรหายไปจากฐานข้อมูล

expect(Resource.find_by(id: resource.id)).to be_nil

ทดสอบว่าจำนวน DB เปลี่ยนแปลง

expect { delete :destroy, id: resource.id }.to change(Resource, :count).by(-1)
person Kristján    schedule 07.05.2015
comment
ขอบคุณ! มันสมเหตุสมผลมาก และคำถามของฉันก็โง่มาก... ฉันมองหาข้อผิดพลาดผิดที่เลย - person iacobSon; 07.05.2015
comment
ฉันเคยทำสิ่งนี้กับตัวเองมาแล้วมากมายในอดีต :-D มันเป็นสิ่งง่าย ๆ ที่ทำให้คุณเดินทางได้นานที่สุดเสมอ - person Kristján; 07.05.2015