Ruby on rails 防止特定it块的RSpec隐式主题
我有一个名为Ruby on rails 防止特定it块的RSpec隐式主题,ruby-on-rails,ruby,ruby-on-rails-4,rspec,specifications,Ruby On Rails,Ruby,Ruby On Rails 4,Rspec,Specifications,我有一个名为Item的模型规范: describe Item do it { should have_db_column :name } it { should have_db_column :description } it { should have_db_column :price } # etc … describe '.by_popularity' do it "returns all items in order of popularity" do
Item
的模型规范:
describe Item do
it { should have_db_column :name }
it { should have_db_column :description }
it { should have_db_column :price }
# etc …
describe '.by_popularity' do
it "returns all items in order of popularity" do
@items = 3.times.map { create(:item) }
2.times.map { create(:order, item: @items[0]) }
3.times.map { create(:order, item: @items[1]) }
1.times.map { create(:order, item: @items[2]) }
expect(Item.by_popularity).to eq([@items[1], @items[0], @items[2]])
end
end
end
对于.by\u popularity
范围之前的所有测试,一切都非常有效。RSpec隐式创建一个新的项
,该项用作it
/主题
但是,在测试范围内的.by\u popularity
测试中,我不希望额外的项在调用项的返回值中突然出现,从而导致断言失败
如何防止RSpec为此特定的描述块创建此隐式模型?
我曾尝试声明一个主题,将其设置为空对象,将其设置为nil等,但RSpec仍然创建了一个项
模型
我目前的解决方法是调用项。在it
块的开头删除\u all
,但显然这并不理想。通过使用类名作为description
的第一个参数,RSpec将(惰性地)为您范围内的每个示例实例化该类的实例,如中所述
但是,它本身并没有做任何事情来持久化实例,因此,如果在预期失败时存在四个持久化的项
,那么这是由于其他原因造成的(例如,数据库中预先存在的,或者由测试中以前执行的示例创建的,并且没有清理)。是否使用数据库清理器?是的。我使用数据库清理器,然后您可以向其添加选项。向您展示DC配置?我相信这种rspec用法已被弃用,取而代之的是expect
is not?@Max it not弃用。看来你是对的。RSpec使用new
,而不是create
。莫名其妙的是,问题今天已经解决了,所以你还是去买糖果吧。