使用 let 整理

我們注意到

user = create(:user)course = build(:course) 重複出現。

其實我們可以用 let 去整理。

按照下面的 diff 修改 spec/controllers/courses_controller_spec.rb

diff --git a/spec/controllers/courses_controller_spec.rb b/spec/controllers/courses_controller_spec.rb
index fc68649..a8c083e 100644
--- a/spec/controllers/courses_controller_spec.rb
+++ b/spec/controllers/courses_controller_spec.rb
@@ -41,10 +41,10 @@ RSpec.describe CoursesController, type: :controller do

   describe "GET new" do
     context "when user login" do
-      it "assigns @course" do
-        user = create(:user)
-        course = build(:course)
+      let(:user) { create(:user) }
+      let(:course) { build(:course) }

+      it "assigns @course" do
         sign_in user
         get :new

@@ -52,9 +52,6 @@ RSpec.describe CoursesController, type: :controller do
       end

       it "renders template" do
-        user = create(:user)
-        course = build(:course)
-
         sign_in user
         get :new

其實 let(:user) { create(:user) } 大略等同於:

def user
  @_user ||= create(:user)
end

那用 let 定義的 user & course 在那裡可以用呢?

describe "GET new" do
  context "when user login" do
    let(:user) { create(:user) }
    let(:course) { build(:course) }

    it "assigns @course" do
      ...
    end

    it "renders template" do
      ...
    end
  end

  context "when user not login" do
    ...
  end
end

這樣看就很清楚 user & course 只在 context "when user login" do 區塊裡可以用。

results matching ""

    No results matching ""