简体   繁体   English

在 rspec 中正确存根方法

[英]Stubbing a method correctly in rspec

I'm having trouble trying to stub a method.我在尝试存根方法时遇到了麻烦。 I have the following job:我有以下工作:

AnimalRelationJob动物关系工作

def perform(user_id, animal_id)
  user = User.find(User_id)
  animal_data = Animal::Zoo.internal_data(animal_id)
  owner_score = OwnerService.new.generate_score!(animal_data, user)

  AnimalMailer.animal_tips_message(user, owner_score).deliver_later
end

I want to stub both the internal_data method and OwnerService.generate_score and test that the job was able to call AnimalMailer.animal_tips_message with the correct parameters我想存根internal_data方法和OwnerService.generate_score并测试作业是否能够使用正确的参数调用 AnimalMailer.animal_tips_message

let(:m) { AnimalRelationJob.new.perform(user_id, animal_id) }

before { 
  allow(OwnerAuth::Validation).to receive(:create_key) { true }
  allow_any_instance_of(OwnerService.new).to receive(:generate_score).and_return(100)
  allow(Animal::Zoo).to receive(:internal_data).and_return(1)

}

it "should call the mailer" do
  expect(m).to receive(animal_tips_message).with(admin_user, 100)
end

I'm now getting the error:我现在收到错误:

undefined method `ancestors' for #<OwnerService:0x0029812>

I think it might be coming from me stubbing a method from the OwnerService initialize我认为它可能来自我从 OwnerService 初始化中存根的方法

class OwnerService

  def initialize
    validated = OwnerAuth::Validation.create_key(....)
  end

But the above keeps making a call to the OwnerService class.但是上面一直在调用 OwnerService class。 What am I doing wrong?我究竟做错了什么?

You're stubbing the method on a temp object, the one you get from OwnerService.new .您正在临时 object 上存根该方法,这是您从OwnerService.new获得的方法。 Then perform creates another temp object (that doesn't have any stubs, naturally) and calls the method.然后perform创建另一个临时 object (自然没有任何存根)并调用该方法。

A few ways to go around this: go 的几种方法:

  1. Hijack object creation劫持 object 创建

    fake = double allow(OtherService).to receive(:new).and_return(fake) allow(fake).to receive(:generate_score).and_return(100)
  2. Stub all instances存根所有实例

     allow_any_instance_of(OtherService).to receive(:generate_score).and_return(100)
  3. Reorganize code so that it's more testable ( dependency injection , etc.)重新组织代码,使其更具可测试性( 依赖注入等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM