【问题标题】:rspec/datamapper - how do I tell rspec to expect an error?rspec/datamapper - 我如何告诉 rspec 期待一个错误?
【发布时间】:2013-08-21 21:52:22
【问题描述】:

我目前正在 Sinatra/Datamapper 中测试这个类

class Score 
include DataMapper::Resource

property :score, Integer

property :created_at, DateTime, :default => DateTime.now, :lazy => [:show]
property :updated_at, DateTime, :default => DateTime.now, :lazy => [:show]

belongs_to :pageant, :key => true
belongs_to :candidate, :key => true
belongs_to :category, :key => true
belongs_to :judge, :key => true

end

通过这个 rspec 测试

it 'that can be inserted by a judge if a pageant is active' do
        score_count = Score.all.length
        post '/score', @correct_score_data
        Score.all.length.should eq score_count+1
    end

    it 'cannot be duplicated if it has been sent' do
        score_count = Score.all.length
        post '/score', @correct_score_data
        Score.all.length.should eq score_count
    end

基本上应该发生的是,法官只能为特定类别+候选人+选美组合发送一次分数,之后我想否认下一个分数。现在,当我运行它时,我得到一个 IntegrityError (这是我所期望的)。我如何告诉 rspec 我“希望看到这个错误”?你们也可以批评我的代码,我还在一起学习所有这些

【问题讨论】:

标签: ruby-on-rails ruby testing rspec ruby-datamapper


【解决方案1】:

使用expect{}.to raise_errorhttps://www.relishapp.com/rspec/rspec-expectations/v/2-6/docs/built-in-matchers/raise-error-matcher

我不完全了解您的规格(看起来您的应用程序状态在两个测试之间泄漏),但是像这样......

it 'cannot be duplicated if it has been sent' do
    score_count = Score.all.length
    expect { post '/score', @correct_score_data }.to raise_error(IntegrityError)
end

【讨论】:

  • 试过了,现在可以了。您是什么意思应用程序状态在两个测试之间泄漏?
  • 嗯,您发布的两个规范看起来做的事情完全相同,但预期的结果却不同。除非您没有发布更多信息,否则我假设您希望运行一个测试并成功,然后运行下一个测试并将应用程序推入“坏”状态。两个规格不应该要求彼此工作。如果不是这样,那我只是假设太多了!
  • 啊,是的,应该发生的是发送一个,它有效,发送相同的东西,它不起作用......我想我需要阅读更多
猜你喜欢
  • 2014-04-06
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
相关资源
最近更新 更多