首页 > 解决方案 > NoMethodError:RSpec 中 nil:NilClass 的未定义方法“customer_details”

问题描述

我的 RSpec 测试失败了,但我不知道如何解决这个问题。在 Class pass 上调用.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

规范

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

任何帮助将不胜感激。

标签: ruby-on-railsrubyrspecrspec-rails

解决方案


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

确保您正在创建的商店

    @shop = create(:shop)

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


推荐阅读