检查.empty?毁灭后不工作

时间:2017-03-10 16:13:12

标签: ruby-on-rails ruby minitest

我写了一个测试,检查来自同一公司内用户的推荐。在断言中,我检查引用是否为空,然后在最终检查引用为空之前运行destroy_referrals方法。 assert referrals.empty?正在返回失败,

1) Failure: CompanyTest#test_destroy_referrals_with_referrals [test/models/company_test.rb:634]: Expected false to be truthy.

company_test.rb

def test_destroy_referrals_with_referrals
    company = companies(:default)
    referrals = company.users.map {|u| u.referrals unless u.referrals.empty?}.uniq.compact

    assert !referrals.empty?
    company.destroy_referrals
    assert referrals.empty?
end

我原以为最后一个断言会确认推介已被删除。任何想法导致失败的想法?

2 个答案:

答案 0 :(得分:3)

问题在于您提前准备了推荐并且从未改变过它。要使测试通过,您应该重新加载它们:

def test_destroy_referrals_with_referrals
    company = companies(:default)
    referrals = -> { company.users.map(&:referrals).reject(&:empty?) }

    assert !referrals.().empty?
    company.destroy_referrals
    assert referrals.().empty?
end

答案 1 :(得分:2)

引荐是一个数组对象。你加载了一次,它留在内存中。你为什么期望它改变?

重新阅读。

referrals = company.users.map {|u| u.referrals unless u.referrals.empty?}.uniq.compact

assert !referrals.empty?
company.destroy_referrals

company.reload # just for good measure
referrals = company.users.map {|u| u.referrals unless u.referrals.empty?}.uniq.compact
assert referrals.empty?