在 Rspec 中模拟一个实例方法
Mocking an instance method in Rspec
我正在 Rails
中使用 Rspec 测试 ruby class
class VolumeAnalysis
class 有一个调用活动记录的方法
returned_volumes
此方法从活动记录中获取一组项目,return类似于:
[
<struct volumeAnalysis::Entry date="2019-12-03", volume=0.3864511633501078e4, predicted=0.143488366498922e3>,
<struct volumeAnalysis::Entry date="2019-12-04", volume=0.3699056933789016e4, predicted=0.165454699712062e3>,
....
....
....
.... ]
我想测试的class中的其他方法依赖于这个方法,如何模拟这个方法return值?
尝试这样的事情:
allow(volume_analysis).to receive(:returned_volumes) { and_then_create_your_entry_structs_here }
def and_then_create_your_entry_structs_here
[VolumeAnalysis::Entry.new(DateTime.current, 0.123, 0.123)]
# this is quick and dirty - you'll have to create the Entry objects properly
end
我正在 Rails
中使用 Rspec 测试 ruby classclass VolumeAnalysis
class 有一个调用活动记录的方法
returned_volumes
此方法从活动记录中获取一组项目,return类似于:
[
<struct volumeAnalysis::Entry date="2019-12-03", volume=0.3864511633501078e4, predicted=0.143488366498922e3>,
<struct volumeAnalysis::Entry date="2019-12-04", volume=0.3699056933789016e4, predicted=0.165454699712062e3>,
....
....
....
.... ]
我想测试的class中的其他方法依赖于这个方法,如何模拟这个方法return值?
尝试这样的事情:
allow(volume_analysis).to receive(:returned_volumes) { and_then_create_your_entry_structs_here }
def and_then_create_your_entry_structs_here
[VolumeAnalysis::Entry.new(DateTime.current, 0.123, 0.123)]
# this is quick and dirty - you'll have to create the Entry objects properly
end