我有一個嘲笑的問題。我有班級DistanceMatrix,我想 喜歡指出在if/else 語句中調用了form_matrix的哪個方法。我需要使用摩卡和RSpec。有任何想法嗎?紅寶石。嘲笑RSpec
它試圖:
describe DistanceMatrix, "when mocking ..." do
it "should do call form_matrix" do
DistanceMatrix.any_instance.expects(:form_matrix).with([1]).once
DistanceMatrix.any_instance.expects(:get_data_from_yaml).with("file_name.yml").once.returns([1])
DistanceMatrix.new("file_name.yml")
end
end
,但得到的錯誤:
Failures:
1) DistanceMatrix when mocking ... should do call form_matrix
Failure/Error: DistanceMatrix.new("file_name.yml")
unexpected invocation: #<AnyInstance:DistanceMatrix>.get_data_from_yaml('file_name.yml', nil)
unsatisfied expectations:
- expected exactly once, not yet invoked: #<AnyInstance:DistanceMatrix>.get_data_from_yaml('file_name.yml')
- expected exactly once, not yet invoked: #<AnyInstance:DistanceMatrix>.form_matrix([1])
satisfied expectations:
- allowed any number of times, already invoked once: #<DistanceMatrix:0x9e48b40>.get_optimal_route(any_parameters)
- allowed any number of times, already invoked once: #<Database::Distances:0x9d59798>.load_distances(any_parameters)
# ./distance_matrix.rb:18:in `initialize'
# ./tsp_algorithm_spec.rb:253:in `new'
# ./tsp_algorithm_spec.rb:253:in `block (2 levels) in <top (required)>'
Finished in 0.25979 seconds
我發現,在我們的RSpec應該使用不.expects(),但.should_receive(),所以我嘗試:
describe DistanceMatrix, "when mocking ..." do
it "should do call form_matrix" do
DistanceMatrix.any_instance.should_receive(:form_matrix).with([1])
DistanceMatrix.any_instance.should_receive(:get_data_from_yaml).with("file_name.yml").and_return([1])
DistanceMatrix.new("file_name.yml")
end
end
但得到了新的失敗:
Failures:
1) DistanceMatrix when mocking ... should do call form_matrix
Failure/Error: DistanceMatrix.any_instance.should_receive(:form_matrix).with([1])
(#<Mocha::ClassMethods::AnyInstance:0x96356b0>).form_matrix([1])
expected: 1 time
received: 0 times
# ./tsp_algorithm_spec.rb:251:in `block (2 levels) in <top (required)>'
Finished in 0.26741 seconds
#should_receive使用的RSpec的嘲弄 - 你原本說你用摩卡。如果你想使用摩卡,你應該在你的項目的spec_helper.rb中進行配置。 – karmajunkie 2010-12-01 20:16:34
這兩個錯誤告訴你的是,form_matrix沒有按照你的預期調用。我認爲問題不在您的測試中。我的猜測是,你傳遞給初始化器的東西是一個包裝的字符串或者其他東西,所以args [0] .class!= String。你有沒有在調試器中逐步瞭解它是怎麼回事? – karmajunkie 2010-12-01 20:22:02