【问题标题】:Uninitialized constant NameError in RspecRspec中未初始化的常量NameError
【发布时间】:2020-07-13 11:28:48
【问题描述】:

当我运行 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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我会使用来自 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  
      

      【讨论】:

      • 你的spec文件的文件夹结构和原来的一样吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多