使用者 destroy course 的話,必須是當初創作者才可以刪除

先修改測試 spec/controllers/courses_controller_spec.rb

diff --git a/spec/controllers/courses_controller_spec.rb b/spec/controllers/courses_controller_spec.rb
index 0200b91..e1e4542 100644
--- a/spec/controllers/courses_controller_spec.rb
+++ b/spec/controllers/courses_controller_spec.rb
@@ -216,29 +216,46 @@ RSpec.describe CoursesController, type: :controller do
   end

   describe "DELETE destroy" do
-    let(:user) { create(:user) }
-    before { sign_in user }
+    let(:author) { create(:user) }
+    let(:not_author) { create(:user) }

-    it "assigns @course" do
-      course = create(:course)

-      delete :destroy, params: { id: course.id }
+    context "when sign in as author" do
+      before { sign_in author }

-      expect(assigns[:course]).to eq(course)
-    end
+      it "assigns @course" do
+        course = create(:course, user: author)

-    it "deletes a record" do
-      course = create(:course)
+        delete :destroy, params: { id: course.id }
+
+        expect(assigns[:course]).to eq(course)
+      end
+
+      it "deletes a record" do
+        course = create(:course, user: author)
+
+        expect { delete :destroy, params: { id: course.id } }.to change { Course.count }.by(-1)
+      end
+
+      it "redirects to courses_path" do
+        course = create(:course, user: author)

-      expect { delete :destroy, params: { id: course.id } }.to change { Course.count }.by(-1)
+        delete :destroy, params: { id: course.id }
+
+        expect(response).to redirect_to courses_path
+      end
     end

-    it "redirects to courses_path" do
-      course = create(:course)
+    context "when sign in not as author" do
+      before { sign_in not_author }

-      delete :destroy, params: { id: course.id }
+      it "raises an error" do
+        course = create(:course, user: author)

-      expect(response).to redirect_to courses_path
+        expect do
+          delete :destroy, params: { id: course.id }
+        end.to raise_error ActiveRecord::RecordNotFound
+      end
     end
   end
 end

修改 app/controllers/courses_controller.rb

diff --git a/app/controllers/courses_controller.rb b/app/controllers/courses_controller.rb
index 2e8152a..3973531 100644
--- a/app/controllers/courses_controller.rb
+++ b/app/controllers/courses_controller.rb
@@ -39,7 +39,7 @@ class CoursesController < ApplicationController
   end

   def destroy
-    @course = Course.find(params[:id])
+    @course = current_user.courses.find(params[:id])
     @course.destroy

     redirect_to courses_path

results matching ""

    No results matching ""