我如何使用一个Rspec期望断言为每个测试运行,而不重复自己?

时间:2017-04-01 01:42:51

标签: ruby-on-rails rspec rspec-rails rspec2

我有不同的函数来编写Rspec测试。但问题是,我尝试在这里测试,每个函数都有相同的语法,所以我必须复制粘贴#34;期望"每个测试用例的行。你知道我怎么写这个期望断言一次并适用于每个测试步骤吗?

看看"期待(延迟::工作计数)。到eq(1)"在下面的代码中:

  it 'is able to send reminder email for submission deadline to signed-up users ' do
    mail = DelayedMailer.new(@assignment.id, "submission", @due_at)
    Delayed::Job.enqueue(payload_object: mail, priority: 1, run_at: 1.second.from_now)
    expect(Delayed::Job.count).to eq(1)
    expect(Delayed::Job.last.handler).to include("deadline_type:     submission")
    expect { mail.perform } .to change { Mailer.deliveries.count } .by(1)
  end

  it 'is able to send reminder email for review deadline to reviewers ' do
    mail = DelayedMailer.new(@assignment.id, "review", @due_at)
    Delayed::Job.enqueue(payload_object: mail, priority: 1, run_at: 1.second.from_now)
    expect(Delayed::Job.count).to eq(1)
    expect(Delayed::Job.last.handler).to include("deadline_type: review")
    expect { mail.perform } .to change { Mailer.deliveries.count } .by(1)
  end

  it 'is able to send reminder email for Metareview deadline to meta-reviewers and team members of the assignment' do
    mail = DelayedMailer.new(@assignment.id, "metareview", @due_at)
    Delayed::Job.enqueue(payload_object: mail, priority: 1, run_at: 1.second.from_now)
    expect(Delayed::Job.count).to eq(1)
    expect(Delayed::Job.last.handler).to include("deadline_type: metareview")
    expect { mail.perform } .to change { Mailer.deliveries.count } .by(2)
  end

1 个答案:

答案 0 :(得分:2)

你在这里有两个选择:

1)制作一个包装该逻辑的辅助方法:https://relishapp.com/rspec/rspec-core/v/3-4/docs/helper-methods/define-helper-methods-in-a-module

这个唯一的缺点是你必须在任何你想要的地方调用该方法。

2)使用每个钩子之后:https://relishapp.com/rspec/rspec-core/v/3-4/docs/helper-methods/define-helper-methods-in-a-module

我不推荐这个,因为它会在每个规格之后运行。