我正在尝试为我正在开发的助手构建 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/