用rspec和工厂测试模型方法

时间:2013-03-23 09:59:45

标签: ruby-on-rails rspec factory-bot

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

2 个答案:

答案 0 :(得分:0)

看起来addresses仅在本地范围内,因此每次拨打current_address=时都会将其清除。试试self.addresses

答案 1 :(得分:0)

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

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

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

我认为您应该像在代码addresses << value

中一样添加新元素