NameError:RSpec上的未初始化常量

时间:2018-07-20 13:14:39

标签: ruby-on-rails

我的UserTrainingController中有以下内容

  def create
   @user_training_resource = UserTrainingResource::Create.call(user_training_resource_params)
   respond_with(@user_training_resource)
 end

然后在“操作”>“培训资源”>“创建”

class UserTrainingResource
 class Create < Operation

   def call(params)
     user_training_resource = UserTrainingResource.new(params)
     ResourceMailer.requested(user_training_resource).deliver_later if user_training_resource.save
     user_training_resource
   end

 end
end

然后在我的考试中我有

 require 'rails_helper'

 RSpec.describe UserTrainingResource::Create do

  let(:params) { attributes_for(:user_training_resource) }

  describe '#call' do
    it 'saves the request as pending' do
      ut = UserTrainingResource::Create.call(params)
      expect(ut.persisted?).to eq(true)
    end

    it 'queues a mailer' do
      expect(ResourceMailer).to send_mail(:requested)
      UserTrainingResource::Create.call(params)
    end
  end

end

测试给了我

  

NameError:未初始化的常量UserTrainingResource :: Create

我不知道问题是什么。它不能正确执行我的操作吗?

3 个答案:

答案 0 :(得分:3)

Rails希望在app/models/user_training_resource/create.rb中定义该类,或者您可以将目录添加到config.autoload_paths

https://blog.bigbinary.com/2015/11/05/how-constant-lookup-happens-in-rails.html

答案 1 :(得分:1)

文件结构必须与类的名称匹配。将目录重命名为app/models/user_training_resource/create.rblib/user_training_resource/create.rb

答案 2 :(得分:0)

您应使用module,如下所示:

module UserTrainingResource
  class Create < Operation
    ...
  end
end

或者这样的简写方式:

class UserTrainingResource::Create < Operation
end