[英]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.