我在模型中有一个 getter/setter 方法,用于检索数组的最后一个元素,并添加到数组中(Postgresql 字符串数组):
# 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 ==)
提前致谢
更新:谢谢,我通过测试的修改方法如下:
# 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