NoMethodError: undefined method 'customer_details' for nil:NilClass in RSpec

NoMethodError: undefined method 'customer_details' for nil:NilClass in RSpec

我的 RSpec 测试失败了,但我不知道该如何解决。在 Class 传递上调用 .all 方法,但因关联而失败。

错误信息

  0) CustomerDetail #index when logged in should render customer details index page
     Failure/Error: @customer_details = current_shop.customer_details.load

     NoMethodError:
       undefined method `customer_details' for nil:NilClass
     # ./app/controllers/customer_details_controller.rb:9:in `index'

应用程序控制器

class ApplicationController < ActionController::Base
  layout 'embedded_app'

  def current_shop
    @current_shop ||= Shop.find_by(shopify_domain: cookies[:shopify_domain])
  end
end

这里是控制器

class CustomerDetailsController < ApplicationController
  before_action :authenticate_user!

  def index
    # This failed the test below and complains that NoMethodError: undefined method 'customer_details' for nil:NilClass
    @customer_details = current_shop.customer_details.load

    #This pass the test below
    @customer_details = CustomerDetail.all.load
  end
end

型号

class Shop < ActiveRecord::Base
  include ShopifyApp::SessionStorage

  has_many :customer_details

  def api_version
    ShopifyApp.configuration.api_version
  end
end

class CustomerDetail < ApplicationRecord
  belongs_to :shop
end

RSpec

context 'when logged in' do
  before do
    @shop = create(:shop)
    @user = create(:user)
    sign_in @user
  end

  it 'should return a 200 response' do
    get customer_details_index_path
    expect(response).to have_http_status '200'
  end

  it 'should render customer details index page' do
     get customer_details_index_path
     expect(response).to render_template(:index)
  end
end

如有任何帮助,我们将不胜感激。

current_shop 在您的控制器中是 nil。在规范代码中设置 shop 是不够的。来自规范的实例变量不与被测控制器共享。

确保您在

中创建的商店
    @shop = create(:shop)

已将字段 shopify_domain 设置为测试请求中具有 cookies[:shopify_domain] 的任何值。