Неинициализированная константа NameError в Rspec - PullRequest
0 голосов
/ 01 апреля 2020

Когда я запускаю rails c, я могу вызвать следующий класс и метод работает:

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

Я пытаюсь настроить это в rspe c следующим образом:

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

Ответы [ 2 ]

1 голос
/ 01 апреля 2020

Добавьте это к вашему spec_helper.rb

# spec_helper.rb

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

При запуске RSpe c, Rails не загружается автоматически и, следовательно, не загружает автоматически все библиотеки.

Кроме того, я бы предложил создать .rspec в папке root вашего приложения со следующими строками, чтобы spec_helper автоматически загружался для всех ваших тестов RSpe c:

# .rspec
--format documentation
--color
--require spec_helper
0 голосов
/ 01 апреля 2020

Я бы использовал описанный_класс от Rspe c

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  
...