ruby-on-rails - RSpec——对象*应该*创建一次,而是为每个测试创建

标签 ruby-on-rails ruby unit-testing rspec rspec2

我正在尝试为我正在开发的助手构建 rspec (rspec2) 测试用例。这个助手基本上用“信号”对象做一些事情。在我的应用程序中,“信号”与“作者”相关联。

我在这里遇到的麻烦是,当我使用这样的代码进行测试时:

describe SignalHelper do
  let(:author) { Author.create(author_identifier: "foobar_identifier") }

  specify "should fail to instantiate without an author" do
    lambda { SignalHelper.new }.should raise_error
  end

  specify "should instantiate with a valid author" do
    SignalHelper.new(author)
  end
end

我发现正在创建多个作者并间接导致 SignalHelper 中的代码出现问题。

我该怎么做才能在所有测试运行之前创建一个作者并在每个测试中使用同一作者?

我认为使用 let() 是正确的方法,但显然不是这样。我也尝试过看起来与此类似但没有成功的代码:

describe SignalHelper do
  let(:author) { Author.create(author_identifier: "foobar_identifier") }

  before(:all) do 
    author
  end

  specify "should fail to instantiate without an author" do
    lambda { SignalHelper.new }.should raise_error
  end

  specify "should instantiate with a valid author" do
    SignalHelper.new(author)
  end
end

谢谢!

最佳答案

使用#let 是正确的方法,因为它确保您不会在规范示例之间共享测试对象的状态。如果您出于某种原因无法创建多个作者,则只需创建一个作为 ivar:

describe SignalHelper do
  before(:all) { @author = Author.create(author_identifier: "foobar_identifier") }

  specify "should fail to instantiate without an author" do
    lambda { SignalHelper.new }.should raise_error
  end

  specify "should instantiate with a valid author" do
    SignalHelper.new(@author)
  end
end

关于ruby-on-rails - RSpec——对象*应该*创建一次,而是为每个测试创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7302936/

相关文章:

ruby-on-rails - Rails 互斥字段

unit-testing - 将 PHPUnit 与 CakePHP 1.3 集成

unit-testing - 基于属性的异常测试

c# - ReactiveUI:为什么在使用 TestScheduler 时必须在 "...Throttle..."中明确指定调度程序

ruby-on-rails - 从 Rails 的 time_select() 中去除不需要的值

ruby-on-rails - nginx和thin的区别

ruby-on-rails - 使用 rspec 调用特定的 url

mysql - Ruby on Rails。无法在数据库中创建记录

Ruby - 遍历数据库结果并将它们存储在哈希中

ruby-on-rails - ActiveAdmin 在重命名的资源上设置 Permit_params