简体   繁体   中英

testing model methods with rspec and factory

I have a getter/setter method in a model retrieving the last element of an array, and adding to the array (Postgresql array of strings):

# 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

The methods appear to be working correctly. I'm learning Rspec / Factory and trying to test this. The tests are failing and I'd be grateful for some advice on how I should do this:

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 ==)

Thanks in advance

UPDATE: Thank you, my amended methods which pass the test are below:

# 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

It looks like addresses is only in local scope, so every time you call current_address= it will be cleared. Try self.addresses .

Here's what I think it's wrong.

In your test instead of adding an element to the array you are replacing it because you are assigning a new value to it.

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

What I think you should do is add a new element as you do in your code addresses << value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM