Ruby on rails Rspec:在类中调用某个方法之前执行某些操作

Ruby on rails Rspec:在类中调用某个方法之前执行某些操作,ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,我有一门课,例如: class BackgroundJob def run pre_processing processing end def preprocessing end def processing end end 所以我的代码将运行:BackgroundJob.new.run。在我的rspec中,我想在调用processing方法之前做一些“事情”。我怎样才能在rspec中做到这一点 感谢RSpec中的,与其他任何地方一样,这可以通过使用

我有一门课,例如:

class BackgroundJob
  def run
    pre_processing
    processing
  end

  def preprocessing
  end

  def processing
  end
end
所以我的代码将运行:
BackgroundJob.new.run
。在我的rspec中,我想在调用
processing
方法之前做一些“事情”。我怎样才能在rspec中做到这一点


感谢RSpec中的

,与其他任何地方一样,这可以通过使用:

这种方法有一个缺点:修改后的类将保留在预先指定的模块中,无法“取消”已经预先指定的模块


另一种方法是使用。好的,
pass_-thru
可能只会将额外的代码附加到方法中,因此应该
flexmock
预处理
方法:

BackgroundJob.should_receive(:preprocessing).pass_thru do |job|
  job.tap do |job|
    puts "do_stuff"
  end
end
BackgroundJob.should_receive(:preprocessing).pass_thru do |job|
  job.tap do |job|
    puts "do_stuff"
  end
end