2014-02-11 21 views
4

我不能在我的一個測試中使用match_array來重新匹配空數組。我有以下消息:空數組的rspec match_array失敗?

Failure/Error: expect(subject.custom_text_locations).to be match_array([]) 

    expected #<RSpec::Matchers::BuiltIn::MatchArray:105810100> => #<RSpec::Matchers::BuiltIn::MatchArray:0xc9d1168 @expected=[]> 
     got #<Array:105810180> => [] 

這裏是我的測試:

context 'when there is no custom text locations' do 
    subject { create(:service, custom_text_locations: nil) } 
    it 'returns empty list' do 
    expect(subject.custom_text_locations).to match_array([]) 
    end 
end 

如果我通過be_empty改變match_array([]),我的代碼工作。另外,正如@PeterAlfvin指出的那樣,將custom_text_locations初始化更改爲[]似乎可行。

這是我的方法:

def custom_text_locations 
    self[:custom_text_locations] || [] 
end 

問:什麼是錯我的測試?

+0

這很奇怪。如果用'[]'替換'subject.custom_text_locations',它會通過嗎?如果你在'expect'前面打印'subject.custom_text_locations.inspect',你會得到什麼? –

+0

另外,您使用的是什麼版本的RSpec? –

+0

@PeterAlfvin你說得對,如果我用'[]'替換它的工作。 rspec版本'2.14.7'。我也加了這個方法,因爲它似乎涉及到這個問題。 – fotanus

回答

9

您發佈的代碼不生成您發佈的錯誤代碼。

您發佈的錯誤包含錯誤的to be match_array([]),這與您發佈的代碼中正確的to match_array([])有很大不同。

+0

你是一個先見之人嗎? :O – fotanus

+0

我不接受你的答案,那麼我可以獎勵你與賞金獵人一些額外的積分。 – fotanus

+1

幾乎不是一個先見者,更像一個盲人。 ;-)我一直在盯着和失去這種差異的時間超過了我所承認的時間! –