1

帮助我通过这个测试:

这是一些 rspec 代码的示例,

class User
  attr_accessor :count
  
  def initialize
    @count = 0
  end

  # sometimes raises
  def danger
    puts "IO can be dangerous..."
  rescue IOError => e
    @count += 1
  end
  
  #always raises
  def danger!
    raise IOError.new    
  rescue IOError => e
    @count += 1
  end
end

describe User do  
  describe "#danger!" do
    it "its rescue block always increases the counter by one" do
      allow(subject).to receive(:'danger!')
      
      expect {
        subject.danger!
      }.to change(subject, :count).by(1)
    end
  end

  describe "#danger" do
    context "when it rescues an exception" do
      it "should increase the counter" do
        allow(subject).to receive(:danger).and_raise(IOError)
        
        expect {
          subject.danger
        }.to change(subject, :count).by(1)
      end      
    end
  end
end

我还创建了一个包含这些测试的小提琴,所以你可以让它们通过。请帮我测试一个方法的救援块!


背景:

我原来的问题是这样的:

我有一个方法,如下所示:

def publish!(resource)
  published_resource = resource.publish!(current_project)

  resource.update(published: true)

  if resource.has_comments?
    content = render_to_string partial: "#{ resource.class.name.tableize }/comment", locals: { comment: resource.comment_content_attributes }

    resource.publish_comments!(current_project, published_resource.id, content)
  end

  true

  rescue Bcx::ResponseError => e
    resource.errors.add(:base, e.errors)

    raise e
  end

我想测试一下resource.errors.add(:base, e.errors),实际上是在资源中添加了一个错误。更一般地说,我想在一个方法中测试救援块。

所以我想写这样的代码,

it "collects errors" do 
  expect{ 
    subject.publish!(training_event.basecamp_calendar_event)
  }.to change(training_event.errors.messages, :count).by(1)
end

当然,这会引发错误,因为我在救援区块中重新加注。

我见过一些使用 old 的答案something.stub(:method_name).and_raise(SomeException),但 rspec 抱怨这种语法已被弃用。我想使用Rspec Mocks 3.3allow语法,但我很难过。

4

2 回答 2

4
allow(something).to receive(:method_name).and_raise(SomeException)

将是新的allow语法。查看文档以供参考。

于 2015-08-21T02:41:53.800 回答
0

我误解了allow语法的实际用途。所以为了让我的示例规范通过,我需要这样做:

describe "#danger" do
  context "when it rescues an exception" do
    it "should increase the counter" do
      allow($stdout).to receive(:puts).and_raise(IOError) # <----- here

      expect {
        subject.danger
      }.to change(subject, :count).by(1)
    end      
  end
end

我要插入的东西不是方法或主题,而是可能引发的对象。在这种情况下,我存根$stdout,以便看跌期权会提高。

这是规范通过的另一个小提琴

于 2015-08-21T15:55:43.110 回答