2011-04-29 115 views
1

代碼迴路行爲:測試使用Rspec的

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是UserImage

的主鍵

如何測試下面的測試案例?:

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

end 

回答

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

評論後

這個怎麼

# 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 
+0

我想測試以下,如果UniqueId.generate [0..7] retrives這是由一些其它的記錄中的UID,調用UniqueId.generate [0..7]再次 – ddayan 2011-04-29 16:19:49