【发布时间】:2016-10-26 05:14:38
【问题描述】:
我是 RSpec 的新手。我的模型 user_profile.rb 中有一个方法
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 表中,我只有一列:name。
user_profile.save 失败时如何测试案例? 这里最重要的问题是我没有找到任何方法让这个 user_profile.save 失败。
有些人建议使用 RSpec 存根。我们如何做到这一点?
【问题讨论】:
标签: ruby-on-rails ruby rspec exception-handling