我想使用RSpec模拟来为代码块提供预先设定的输入。
Ruby:
RSpec:
这是一种通过向块传递固定数据来测试其内部是否正常工作的方法。但我不知道如何使用 RSpec 的模拟机制进行实际的数据输入。
更新:看起来问题并不在于 linetext,而是在于:
这句话的意思是:“这不是被称为的方式,用self.extracted=来替换Ruby代码中的它会有所帮助,但感觉有些不对。”
Ruby:
class Parser
attr_accessor :extracted
def parse(fname)
File.open(fname).each do |line|
extracted = line if line =~ /^RCS file: (.*),v$/
end
end
end
RSpec:
describe Parser
before do
@parser = Parser.new
@lines = mock("lines")
@lines.stub!(:each)
File.stub!(:open).and_return(@lines)
end
it "should extract a filename into extracted" do
linetext = [ "RCS file: hello,v\n", "bla bla bla\n" ]
# HELP ME HERE ...
# the :each should be fed with 'linetext'
@lines.should_receive(:each)
@parser.should_receive('extracted=')
@parser.parse("somefile.txt")
end
end
这是一种通过向块传递固定数据来测试其内部是否正常工作的方法。但我不知道如何使用 RSpec 的模拟机制进行实际的数据输入。
更新:看起来问题并不在于 linetext,而是在于:
@parser.should_receive('extracted=')
这句话的意思是:“这不是被称为的方式,用self.extracted=来替换Ruby代码中的它会有所帮助,但感觉有些不对。”