【发布时间】:2016-09-23 02:29:52
【问题描述】:
我在使用以下代码时遇到问题,它只在我运行它的某些时候通过。
require_relative 'spec_helper'
require 'pry'
RSpec.describe Round do
testFruit = [Fruit.create(name: "Anjou Pear", unit: "10/LB", price: 13.24), Fruit.create(name: "Anjou Bear", unit: "10/LB", price: 15.24)]
before(:each) do |variable|
@round = Round.new
end
it 'returns all fruit in the current round of ordering' do
expect(@round.fruits).to match_array(testFruit)
end
it 'lets you clear the list for the next round' do
@round.next
expect(@round.fruits).to match_array([])
end
end
@round.fruits 定义为
def fruits
Fruits.all
end
所以我理解Fruits.all 必须等待 testFruits 被持久化到数据库中,我猜这没有及时完成?有没有办法可以用 rspec 异步测试这个,我应该以不同的方式设计我的测试以避免这个问题吗?
我得到的错误是 ``` 失败/错误:expect(@round.fruits).to match_array(testFruit)
expected collection contained: [#<Fruit id: 53, pic: nil, description: nil, name: "Anjou Pear", unit: "10/LB", price: #<BigDecimal:2...l:206de28,'0.1524E2',18(27)>, created_at: "2016-09-27 18:18:23", updated_at: "2016-09-27 18:18:23">]
actual collection contained: []
```
【问题讨论】:
-
将 testFruit = [...] 移到 before(:each) 中作为 @testFruit = [...] 并且它应该可以工作,您不要在示例之外或之前创建对象( :each) 块或将留在数据库中
-
所以在 before(:each) 块中创建的对象被删除/不会在运行规范后保留在数据库中?
-
是的,在 before(:each) 块中创建的对象不会在下一个规范中持续存在。如果你在 before(:each) 之外创建了一些东西(例如 before(:all) ),你必须在你的规范之后删除它(使用 after(:all) 块)或使用数据库清理器 gem(如 DatabaseCleaner )或者你'最终会得到一个充满旧运行垃圾的测试数据库。
标签: ruby activerecord rspec