有关存根和模拟测试的帮助,如何使用必须返回值的模拟?

时间:2011-06-05 20:58:36

标签: ruby rspec

我想测试的方法是:

def self.load_file(file)
  lookup = ''

  if file.extension.include? "abc"
    lookup = file.extension
  else
    lookup = file.last_updated
  end  

  @location = Location.find_by_lookup(lookup)

  @location
end

所以我需要存根文件,以便它响应扩展和last_updated调用。 我还需要模拟对file.last_updated的调用,因为我想确保如果文件扩展名为'abc',它不会通过扩展名查找,而是通过'last_updated'查找。

我该如何测试?

1 个答案:

答案 0 :(得分:1)

您的流程看起来像这样(将“MyClass”替换为您班级的实际名称):

it "should lookup by last_updated for abc files" do
  update_time = Time.now
  # create a location to match this update_time here
  file = double("file")
  file.should_receive(:extension).and_return("abc")
  file.should_receive(:last_update).and_return(update_time)
  MyClass.load_file(file).should == Location.find_by_lookup(update_time)
end

it "should lookup by extension for all other files" do
  # create a location to match the "def" extension here
  file = double("file")
  file.should_receive(:extension).twice.and_return("def")
  file.should_not_receive(:last_update)
  MyClass.load_file(file).should == Location.find_by_lookup("def")
end