我有一個模型的吸氣劑/ setter方法檢索的陣列的最後一個元素,並添加到陣列(字符串的PostgreSQL的數組):使用RSpec和工廠測試模型的方法
# return the last address from the array
def current_address
addresses && addresses.last
end
# add the current address to the array of addresses
# if the current address is not blank and is not the same as the last address
def current_address=(value)
addresses ||= []
if value && value != addresses.last
addresses << value
end
write_attribute(:addresses, addresses)
end
的方法出現要正常工作。我正在學習Rspec/Factory並試圖對此進行測試。測試失敗,我會很感激一些建議,我應該怎麼做:
it "adds to the list of addresses if the student's address changes" do
student = build(:student)
student.current_address = "first address"
student.current_address = "second address"
student.addresses.count.should == 2
end
Failure/Error: student.addresses.count.should == 2
expected: 2
got: 1 (using ==)
it "provides the student's current address" do
student = build(:student)
student.current_address = "first address"
student.current_address = "second address"
student.current_address = ""
student.current_address.should == "second address"
end
Failure/Error: student.current_address.should == "second address"
expected: "second address"
got: "" (using ==)
在此先感謝
UPDATE:謝謝你,它通過測試我的修改方法如下:
# return the last address from the array
def current_address
addresses && addresses.last
end
# add the current address to the array of addresses
# if the current address is not blank and is not the same as the last address
def current_address=(value)
list = self.addresses
list ||= []
if !value.empty? && value != list.last
list << value
end
write_attribute(:addresses, list)
end
謝謝你,在我的重構setter方法,以使其更具可讀性什麼建議嗎?測試通過了,但在最初通過self.addresses重寫了方法之後,通過了所有測試,但在提交學生表單時沒有更新數據庫 - 是否有更好的方法來測試setter實際上是否更新了寫入的數據庫只是有興趣,上面的方法正確寫入)。再次感謝 – 2013-03-23 11:29:37
在對象上調用'reload',您將能夠確認地址是否正確保存。 – 2013-03-23 11:54:19
謝謝安迪,工作。 – 2013-03-23 12:31:38