Rails 5 + FactoryGirl + Rspec:未定义的辅助方法

时间:2017-02-15 08:58:29

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

我要运行此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测试时使用辅助方法?我正确使用帮助方法吗?

祝你好运

1 个答案:

答案 0 :(得分:1)

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

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

系统和RSpec运行良好