【问题标题】:RSpec undefined method `to_sym'RSpec未定义的方法`to_sym'
【发布时间】:2020-03-05 01:10:23
【问题描述】:

我的班级负责与我要测试的 Jira 公司董事会建立联系。

class

module Jira
  class JiraConnection
    URL = 'https://company_name.atlassian.net/'.freeze

    def call
      JIRA::Client.new(options)
    end

    private

    def options
      {
        username: ENV['USERNAME'],
        password: ENV['PASSWORD'],
        site: URL,
        context_path: '',
        auth_type: :basic,
        use_ssl: true
      }
    end
  end
end

JIRA::Client.new 来自jira-ruby gem。我想测试一下

我的规格:

RSpec.describe Jira::JiraConnection, type: :service do
  subject(:connect) { described_class.new }

  let(:options) do
    {
      username: username_secret,
      password: password_secret,
      site: 'https://company_name.atlassian.net/',
      context_path: '',
      auth_type: :basic,
      use_ssl: true
    }
  end

  let(:username_secret) { ENV.fetch('USERNAME') }
  let(:password_secret) { ENV.fetch('PASSWORD') }

  before do
    allow(JIRA::Client).to receive(:new).with(options)
  end

  it 'connect to Jira API' do
    expect(subject.call).to receive(JIRA::Client)
  end
end

使用上述规格,我遇到了一个错误:

Failure/Error: expect(subject.call).to receive(JIRA::Client)

 NoMethodError:
   undefined method `to_sym' for JIRA::Client:Class
   Did you mean?  to_s

【问题讨论】:

  • receive 需要一个符号作为其第一个参数,表示要调用的方法。你正在通过一个课程JIRA::Client。你到底想用这条线做什么?
  • 我期待与代表 JIRA::Client 类的 Jira 板建立连接。

标签: ruby-on-rails ruby rspec


【解决方案1】:

您正在尝试测试方法的返回值,但使用expect(...).to receive API,该API 用于测试方法被调用(或者,用于存根方法)。

如果您想检查返回值是否为JIRA::Client 的实例,您可以这样做:

expect(subject.call).to be_a(JIRA::Client)

或者,使用更基本的eq(相等)匹配器:

expect(subject.call.class).to eq(JIRA::Client)

【讨论】:

  • 我收到一个错误:expected: JIRA::Client got: NilClass 这是有线的。
  • 不确定。您的代码有问题。尝试使用调试器。
  • 如果在块之前我将返回一个 instance_double 对象,它将起作用
  • 这是因为你在before钩子中存根new
  • 好渔夫
【解决方案2】:

你可能想要什么:

describe '#call' do
  it 'initializes Jira API client with proper connection options' do
    expect(JIRA::Client).to receive(:new).with(options).once
    connect.call
  end

  it 'returns Jira API client' do
    expect(connect.call).to be_a(JIRA::Client)
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-17
    • 2014-01-12
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    相关资源
    最近更新 更多