Ruby on rails RSpec--Object*应该*创建一次,而不是为每个测试创建
我正在尝试为我正在开发的助手构建rspec(rspec2)测试用例。这个助手基本上处理“信号”对象。在我的应用程序中,“信号”与“作者”关联 我在这里遇到的问题是,当我使用这样的代码进行测试时:Ruby on rails RSpec--Object*应该*创建一次,而不是为每个测试创建,ruby-on-rails,ruby,unit-testing,rspec,rspec2,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 auth
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
在我的例子中,
database\u cleaner
gem在每次测试后删除记录,因此let()
正在重新创建记录
config.after(:each){DatabaseCleaner.clean}
用另一个对象实例化助手似乎有点可疑。也许有更好的方法来实现你的目标。如果你有兴趣探索这一点,你也可以发布你的帮助代码。比灵顿,不幸的是,我无权发布它,我破解了这段代码,它“代表”了我的问题。我认为核心问题是我不确定如何在所有测试中使用相同的对象,而不是为每个测试创建一个新的实例。嗨,David,谢谢你的链接。实际上,我正在使用database_cleaner,但已将其删除,并将rspec设置回config.use_transactional_fixtures=true
,以尝试隔离问题,但仍然没有成功。我是否应该担心我正在使用specify
而不是it
与config.use\u transactional\u fixtures=true
?