ddayan
ddayan

Reputation: 4142

Testing a loop behaviour using Rspec

The code:

def self.api_create(params)
  user_image = UserImage.new(params)
  begin
    user_image.uid = UniqueId.generate[0..7]
  end 

  while not(UserImage.find_all_by_uid(user_image.uid).empty?)
    return user_image
  end
end

unique_id is the primary key of UserImage

How can test the following test case?:

it "should create a new unique id if the one generated is already in use." do

end

Upvotes: 1

Views: 1005

Answers (1)

Tomasz Stanczak
Tomasz Stanczak

Reputation: 13164

params = ...
user_image = UserImage.api_create(params)
UserImage.find_all_by_uid(user_image.id).should be_empty

after comment

what about this

# first call returns 1, second 2
UserImage.stub!(:find_all_by_uid).and_return(1,2) 

# first call returns 1 so that the method needs another call
UniqueId.stub!(:generate).and_return(1,3)

# let it work (whatever params is)
user_image = UserImage.api_create(params)

# the user id should be 3
user_image.id.should == 3

Upvotes: 1

Related Questions