相关模型在更新后不会更新内存中的值

时间:2013-12-18 18:10:16

标签: ruby-on-rails unit-testing activerecord ruby-on-rails-4

我有一个像求职网站的东西。有Position个模型,每个位置都有很多Offers。当一个报价被接受时,其余报价被拒绝并且头寸被平仓。我对Offer的测试按预期传递,但Position的测试失败,因为is_accepted仍为nil ...

test "accept_offer flips is_accepted bits" do
    p = FactoryGirl.create(:position_with_offers, offers: 3)

    assert_nil e.offers[0].is_accepted # pass
    assert_nil e.offers[1].is_accepted # pass
    assert_nil e.offers[2].is_accepted # pass
    assert_equal false, p.is_closed    # pass

    p.accept_offer(e.offers[0])

    assert_equal true, p.is_closed              # pass
    assert_equal true, e.offers[0].is_accepted  # fail, == nil
    assert_equal false, e.offers[1].is_accepted # fail, == nil
    assert_equal false, e.offers[2].is_accepted # fail, == nil

end

...和...

class Position < ActiveRecord::Base
    has_many :offers, inverse_of: :position

    def accept_offer(_offer)
        offers.each do |o|
            if o.id == _offer.id
                o.accept
            else
                o.reject
            end
            o.reload
        end
        update({ is_closed: true })
    end
end

...和...

class Offer < ActiveRecord::Base
    def accept
        update_column(:is_accepted, true)
    end
    def reject
        update_column(:is_accepted, false)
    end
end

我读过应该调用.reload来刷新模型。我把重装放在一切都没有成功。我尝试了update_allupdate_attributeupdate_column的变体,但优惠始终为nil。有趣的是,如果我puts position.accept_offer中的值,则会呈现正确的值。

要让此测试通过,我需要做什么?

1 个答案:

答案 0 :(得分:0)

重新加载优惠。

assert_equal true, e.offers[0].reload.is_accepted  # fail, == nil
assert_equal false, e.offers[1].reload.is_accepted # fail, == nil
assert_equal false, e.offers[2].reload.is_accepted # fail, == nil