繁体   English   中英

在 rspec 中正确存根方法

[英]Stubbing a method correctly in rspec

我在尝试存根方法时遇到了麻烦。 我有以下工作:

动物关系工作

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

我想存根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

我现在收到错误:

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

我认为它可能来自我从 OwnerService 初始化中存根的方法

class OwnerService

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

但是上面一直在调用 OwnerService class。 我究竟做错了什么?

您正在临时 object 上存根该方法,这是您从OwnerService.new获得的方法。 然后perform创建另一个临时 object (自然没有任何存根)并调用该方法。

go 的几种方法:

  1. 劫持 object 创建

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

     allow_any_instance_of(OtherService).to receive(:generate_score).and_return(100)
  3. 重新组织代码,使其更具可测试性( 依赖注入等)

暂无
暂无

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

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