我的问题:
我试图存根一个返回该类实例的类方法,但是我为名为&#34的测试得到了以下错误;用CSV数据创建了一个实例":
Failures:
1) QuestionData.load_questions creates an instance with CSV data
Failure/Error: expect(question_data_class).to receive(:new).with(data).and_return(question_data_instance)
(QuestionData (class)).new([{:time_limit=>10, :text=>"Who was the legendary Benedictine monk who invented champagne?", :correct_...the world?", :correct_answer=>"Lake Superior", :option_2=>"Lake Victoria", :option_3=>"Lake Huron"}])
expected: 1 time with arguments: ([{:time_limit=>10, :text=>"Who was the legendary Benedictine monk who invented champagne?", :correct_...the world?", :correct_answer=>"Lake Superior", :option_2=>"Lake Victoria", :option_3=>"Lake Huron"}])
received: 0 times
上下文:
代码(如下所示)有效 - QuestionData.load_questions
从CSV文件加载数据,并以数据作为参数调用QuestionData.new
。然而,我对.load_questions
方法的测试是出现上述错误。当它被调用时,QuestionData
类的两倍不会收到.new
的{{1}}存根。
我曾尝试研究如何测试返回另一个存根或实例的存根,但似乎无法找到相关的答案。
我非常感谢任何帮助或建议,非常感谢!
代码:
data
测试文件:
require "csv"
class QuestionData
attr_reader :questions
def initialize(questions)
@questions = questions
end
def self.load_questions(file = './app/lib/question_list.csv', questions = [])
self.parse_csv(file, questions)
self.new(questions)
end
def self.parse_csv(file, questions)
CSV.foreach(file) do |row|
time_limit, text, correct_answer, option_2, option_3 = row[0],
row[1], row[2], row[3], row[4]
questions << { time_limit: time_limit, text: text,
correct_answer: correct_answer, option_2: option_2, option_3: option_3
}
end
end
end
答案 0 :(得分:0)
问题是你正在打电话:
allow(question_data_class).to receive(:load_questions).with(file)
如果您仍然希望执行调用,则需要添加:
and_call_original
因此,将执行原始方法,并且您的代码将在原始块上调用新方法。
但问题是你不需要存在你只需要更改存根的类,因为你在double上调用方法,它会尝试在类中执行它,所以你可能需要将您的第二个测试更改为:
describe '.load_questions' do
it "creates an instance containing CSV data" do
expect(described_class).to receive(:new).with(data).and_return(question_data_instance)
described_class.load_questions(file)
end
end