1

我在模型中有一个 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
4

2 回答 2

0

它看起来addresses只是在本地范围内,所以每次调用current_address=它都会被清除。试试self.addresses

于 2013-03-23T10:31:07.267 回答
0

这就是我认为这是错误的。

在您的测试中,您不是在向数组中添加元素而是替换它,因为您正在为其分配一个新值。

student.current_address = "first address"
student.current_address = "second address"

我认为您应该做的是像在代码中一样添加一个新元素addresses << value

于 2013-03-23T10:48:19.333 回答