【发布时间】:2014-04-09 21:52:47
【问题描述】:
所以我有这个型号代码:
def self.cleanup
Transaction.where("created_at < ?", 30.days.ago).destroy_all
end
还有这个 rspec 单元测试:
describe 'self.cleanup' do
before(:each) do
@transaction = Transaction.create(seller:item.user, buyer:user, item:item, created_at:6.weeks.ago)
end
it 'destroys all transactions more than 30 days' do
Transaction.cleanup
expect(@transaction).not_to exist_in_database
end
end
使用这些工厂:
FactoryGirl.define do
factory :transaction do
association :seller, factory: :user, username: 'IAMSeller'
association :buyer, factory: :user, username: 'IAmBuyer'
association :item
end
factory :old_transaction, parent: :transaction do
created_at 6.weeks.ago
end
end
使用这个 rspec 自定义匹配器:
RSpec::Matchers.define :exist_in_database do
match do |actual|
actual.class.exists?(actual.id)
end
end
当我将规范更改为:
describe 'self.cleanup' do
let(:old_transaction){FactoryGirl.create(:old_transaction)}
it 'destroys all transactions more than 30 days' do
Transaction.cleanup
expect(old_transaction).not_to exist_in_database
end
end
测试失败。我还尝试手动创建一个事务并将其分配给 :old_transaction 与 let() 但这也会导致测试失败。
为什么只有在 before(:each) 块中使用实例变量时才会通过?
提前致谢!
编辑:失败的输出
1) Transaction self.cleanup destroys all transactions more than 30 days
Failure/Error: expect(old_transaction).not_to exist_in_database
expected #<Transaction id: 2, seller_id: 3, buyer_id: 4, item_id: 2, transaction_date: nil, created_at: "2014-02-26 10:06:30", updated_at: "2014-04-09 10:06:32", buyer_confirmed: false, seller_confirmed: false, cancelled: false> not to exist in database
# ./spec/models/transaction_spec.rb:40:in `block (3 levels) in <top (required)>'
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 rspec