我是RSpec的新手。我在我的模型user_profile.rbRSpec測試在rails中引發異常
def self.create_from_supplement(device, structure)
xml = Nokogiri.parse(structure.to_s)
user_profile = nil
auth_type = xml.%('auth_supplement/auth_type').inner_html
if 'user' == auth_type
user_details_str = xml.%('auth_supplement/supplement_data/content').inner_html rescue nil
return nil if user_details_str.blank?
user_details_xml = Nokogiri.parse(user_details_str)
user_name = user_details_xml.%('username').inner_html
user_profile = UserProfile.find_or_initialize_by(name: user_name)
if user_profile.save
device.update_attributes(user_profile_id: user_profile.id)
else
raise "User Profile Creation Failed because of #{user_profile.errors.full_messages}"
end
end
return user_profile
end
我寫一個單元測試用例時user_profile.save無法測試方法,測試案例會想到一個異常升高。但在我的user_profiles表中,我只有一列:名稱。
如何測試user_profile.save失敗時的情況? 這裏最重要的問題是我沒有找到任何辦法讓這個user_profile.save失敗。
一些建議使用RSpec存根。我們如何做到這一點?
這裏的問題是如何讓user_profile.save失敗? – krishna
@krishna看到我編輯的答案 –