【问题标题】:Rails 5 + FactoryGirl + Rspec: helper method undefinedRails 5 + FactoryGirl + Rspec:辅助方法未定义
【发布时间】:2017-02-15 08:58:29
【问题描述】:

我要运行这个 RSpec 文件:

require 'rails_helper'

RSpec.describe FinancialManager::SalaryRecord::SomeRecordsController,
               type: :controller,
               financial_manager: true,
               salary_record: true,
               some_record: true do

  context "GET #index" do
    it "assigns all record in instance variable" do
      some_record =
        FactoryGirl.create(
          :valid_financial_manager_salary_record_some_record
        )
      get :index
      expect(assigns(:financial_manager_salary_record_some_records))
        .to eq([some_record])
    end
  end
end

使用此记录模型的:

class FinancialManager::SalaryRecord::SomeRecord < ApplicationRecord
  sanitize = ->(s) { ActionController::Base.helpers.sanitize(s) }

  validates :level,
            presence: true,
            inclusion: {
              in: sanitize.call("levels")
            },
            numericality: { only_integer: true }
end

上面的模型文件正在调用levels 方法,这是我在helpers 文件夹中定义的辅助方法。当我运行 RSpec 文件时,我得到了这个错误:

Failure/Error:
       FactoryGirl.create(
         :valid_financial_manager_salary_record_some_record
       )

     NoMethodError:
       undefined method `levels' for #<FinancialManager::SalaryRecord::SomeRecord:0x000000077f2db0>

问题是,在运行 RSpec 测试时如何使用辅助方法?我是否正确使用了辅助方法?

最好的问候

【问题讨论】:

    标签: factory-bot ruby-on-rails-5 rspec-rails


    【解决方案1】:

    最后,我在谷歌上搜索了如何在模型中调用辅助方法并找到了解决方案并将我的模型更改为:

    class FinancialManager::SalaryRecord::SomeRecord < ApplicationRecord
      validates :level,
                presence: true,
                inclusion: {
                  in: ApplicationController.helpers.levels
                },
                numericality: { only_integer: true }
    end
    

    系统和 RSpec 运行良好

    【讨论】:

    • 感谢您发布问题的答案,我一直在努力寻找如何从工厂回调中调用帮助程序,这很有效。 +1。你应该接受你自己的答案^^
    猜你喜欢
    • 2014-02-10
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    相关资源
    最近更新 更多