ruby-on-rails - 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
任何帮助将不胜感激。
解决方案
current_shop
在nil
您的控制器中。shop
您在规范代码中设置是不够的。规范中的实例变量不与被测控制器共享。
确保您正在创建的商店
@shop = create(:shop)
将字段shopify_domain
设置为测试请求中的任何值cookies[:shopify_domain]
。
推荐阅读
- curl - 计算和评估 Hp prime 中的卷曲
- flutter - flutter web oauth无法读取令牌
- python - 贝尔曼福特的打印路径
- java - 使用 Java 创建 Websocket 拦截器/操纵器
- python - 将 JSON 反序列化为 Python 对象并稍后再次序列化(JSON 包含键“类”)
- pandas - 在 Pandas 中熔化列分组
- flutter - 图像资源在 Web 上加载良好,但在移动设备上不加载
- android - 在将数据从片段传递到活动时,存在或不存在接口有什么区别?
- swift - 更新可可豆荚后没有 Googlesheets API 命令工作
- microtime - 将 Unixtime 转换为 microtime