配列の最後の要素を取得し、配列 (文字列の Postgresql 配列) に追加するモデルに getter/setter メソッドがあります。
# 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