簡體   English   中英

Rspec 中未初始化的常量 NameError

[英]Uninitialized constant NameError in Rspec

當我運行 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

將此添加到您的 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

我會使用 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