Rspec中的未初始化常量NameError

问题描述 投票:0回答:2

当我运行rails c时,我可以调用以下类,并且该方法有效:

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

我正在尝试像这样在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  

但是我仍然收到错误:

  NameError:
  uninitialized constant SlackService

这与我设置模块的方式有关吗?

我当前的设置:

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

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
ruby module rspec
2个回答
0
投票

我将使用Rspec中的described_class

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  

0
投票

将此添加到您的spec_helper.rb

# spec_helper.rb

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

运行RSpec时,Rails不会自动启动,因此不会自动加载所有库。

此外,我建议使用以下几行在应用程序的根文件夹中创建一个.rspec,以便为所有RSpec测试自动加载spec_helper:

# .rspec
--format documentation
--color
--require spec_helper
© www.soinside.com 2019 - 2024. All rights reserved.