简体   繁体   English

Rspec 中未初始化的常量 NameError

[英]Uninitialized constant NameError in Rspec

When I run rails c, I can call the following class and the method works:当我运行 rails c 时,我可以调用以下类并且该方法有效:

 test = SlackService::BoardGameNotifier
 test.create_alert("test")
  >>method works 

I'm trying to set this up in rspec like this:我正在尝试像这样在 rspec 中设置它:

require 'spec_helper'
require 'slack-notifier'

RSpec.describe SlackService::BoardGameNotifier do
 describe '#notify' do
    @notifier = SlackService::BoardGameNotifier

    it 'pings Slack' do
      error = nil
      message = "test"
      expect(notifier).to receive(:ping).with(message)
      notifier.send_message()
    end
  end
end  

But I keep getting the error:但我不断收到错误消息:

  NameError:
  uninitialized constant SlackService

Does this have to do with how I set up the module?这与我如何设置模块有关吗?

My current setup:我目前的设置:

slack_service/board_game_notifier.rb slack_service/board_game_notifier.rb

module SlackService
    class BoardGameNotifier < BaseNotifier
      WEBHOOK_URL =   Rails.configuration.x.slack.url
      DEFAULT_OPTIONS = {
        channel: "board-games-channel",
        text: "board games alert",
        username: "bot",
      }

      def create_alert(message)
       message #testing
      end
    end
  end

slack_service/base_notifier.rb slack_service/base_notifier.rb

module SlackService
    class BaseNotifier
      include Singleton

      def initialize
        webhook_url = self.class::WEBHOOK_URL
        options = self.class::DEFAULT_OPTIONS

        @notifier = Slack::Notifier.new(webhook_url, options)
      end

      def self.send_message
        message = instance.create_alert("test")
        instance.notify(message)
      end

      def notify(message)
        @notifier.post blocks: message
      end
    end
  end

Add this to your spec_helper.rb将此添加到您的 spec_helper.rb

# spec_helper.rb

ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../config/environment", __dir__)

When running RSpec, Rails doesn't automatically boot up, and therefore doesn't automatically load all the libraries.运行 RSpec 时,Rails 不会自动启动,因此不会自动加载所有库。

Also, I'd suggest creating a .rspec in your app's root folder with the following lines so that spec_helper is automatically loaded for all your RSpec tests:另外,我建议使用以下几行在您的应用程序的根文件夹中创建一个.rspec ,以便为您的所有 RSpec 测试自动加载 spec_helper:

# .rspec
--format documentation
--color
--require spec_helper

I would use the described_class from Rspec我会使用 Rspec 中的描述类

require 'spec_helper'
require 'slack-notifier'

RSpec.describe ::SlackService::BoardGameNotifier do
 describe '#notify' do
    it 'pings Slack' do
      error = nil
      message = "test"
      expect(described_class).to receive(:ping).with(message)
      notifier.send_message()
    end
  end
end  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM