NoMethodError:RSpec中nil:NilClass的未定义方法'customer_details'

时间:2019-11-26 13:22:16

标签: ruby-on-rails ruby rspec rspec-rails

我的RSpec测试失败,但是我不知道该如何解决。在类传递上调用.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'

ApplicationController

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

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

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

确保您要在

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

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