使用者必須登入才能操作 course#update

首先按照下面修改 app/controllers/courses_controller.rb

diff --git a/app/controllers/courses_controller.rb b/app/controllers/courses_controller.rb
index 8fe5ad6..f1654d3 100644
--- a/app/controllers/courses_controller.rb
+++ b/app/controllers/courses_controller.rb
@@ -1,5 +1,5 @@
 class CoursesController < ApplicationController
-  before_action :authenticate_user!, :only => [:new, :create, :edit]
+  before_action :authenticate_user!, :only => [:new, :create, :edit, :update]

   def index
     @courses = Course.all

跑測試:

rspec spec/controllers/courses_controller_spec.rb
...............FFF.F...

Failures:

  1) CoursesController PUT update when course has title assigns @course
     Failure/Error: expect(assigns[:course]).to eq(course)

       expected: #<Course id: 1, title: "Course Name", description: "Description.", created_at: "2016-12-11 16:51:00", updated_at: "2016-12-11 16:51:00", user_id: 1>
            got: nil

       (compared using ==)

  2) CoursesController PUT update when course has title changes value
     Failure/Error: expect(assigns[:course].title).to eq("Title")

     NoMethodError:
       undefined method `title' for nil:NilClass

  3) CoursesController PUT update when course has title redirects to course_path
     Failure/Error: expect(response).to redirect_to course_path(course)

       Expected response to be a redirect to <http://test.host/courses/1> but was a redirect to <http://test.host/users/sign_in>.
       Expected "http://test.host/courses/1" to be === "http://test.host/users/sign_in".

  4) CoursesController PUT update when course doesn't have title  renders edit template
     Failure/Error: expect(response).to render_template("edit")
       expecting <"edit"> but rendering with <[]>

Finished in 0.32515 seconds (files took 2.05 seconds to load)
23 examples, 4 failures

可以發現有關 update 的測試都壞掉了,因為現在我們要求要登入方可修改。

修改 spec/controllers/courses_controller_spec.rb,在執行更新操作前先登入即可:

diff --git a/spec/controllers/courses_controller_spec.rb b/spec/controllers/courses_controller_spec.rb
index 41ad426..a1d4e5d 100644
--- a/spec/controllers/courses_controller_spec.rb
+++ b/spec/controllers/courses_controller_spec.rb
@@ -150,6 +150,9 @@ RSpec.describe CoursesController, type: :controller do
   end

   describe "PUT update" do
+    let(:user) { create(:user) }
+    before { sign_in user }
+
     context "when course has title" do
       it "assigns @course" do
         course = create(:course)

results matching ""

    No results matching ""