rspec测试检查#new是否在类上调用

时间:2017-02-02 21:13:42

标签: rspec

我正在尝试在满足if条件时为以下方法编写测试(创建DispatchMessenger的实例)。

class Telephony
  def self.receive(body, opts = {})

    responder = Responder.find_by_phone(opts[:from])

    if responder
      msg = DispatchMessenger.new(responder)
    else
      send("#{opts[:from]}: #{opts[:body]}", to: Rails.configuration.backup_sms_phone)
    end

  end
end

在rspec中我有这个。

describe '#receive' do

  let(:responder)      { create(:user, :responder, phone: '666-555-4444', name: 'Roy the Responder') }

  it "creates an instance of DispatchMessenger when passed a responder's number" do
    expect(DispatchMessenger).to receive(:new).with(responder)
    Telephony.receive('Body', from: '666-555-4444', body: 'Testing')
  end
end

当我运行测试时,我收到此错误消息。

1) Telephony#receive creates an instance of DispatchMessenger when passed a responder's number
 Failure/Error: expect(DispatchMessenger).to receive(:new).with(responder)
   (<DispatchMessenger (class)>).new(#<User id: 16757, email: "roy.the.responder@gmail.com", name: "Roy the Responder", phone: "6665554444", role: "responder", active: true, long: nil, lat: nil>)
       expected: 1 time with arguments: (#<User id: 16757, email: "roy.the.responder@gmail.com", name: "Roy the Responder", phone: "6665554444", role: "responder", active: true, long: nil, lat: nil>)
       received: 0 times with arguments: (#<User id: 16757, email: "roy.the.responder@gmail.com", name: "Roy the Responder", phone: "6665554444", role: "responder", active: true, long: nil, lat: nil>)

我希望此测试只是确认如果将此特定电话号码传递给Telephony#receive,则会创建DispatchMessenger实例。这是比较对象,我应该在哪里比较一个特定的属性(即电话号码)?如果是这样,我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

您是对的,对象不是==,您应该将属性与have_attributes匹配器进行比较。

let(:responder) { have_attributes(phone: '666-555-4444', name: 'Roy the Responder') }

对于没有值的属性,您可以使用respond_to匹配器。