开发者

How can I disable Active Record Query Caching in Tests? Or use reload smarter?

I have had a lot of headaches in testing recently with what seems to be query caching.

A lot of variables didn't seem to have to values I thought they would, and I discovered that I have to use 'reload'. Now I'm using 'reload' way too often to make sure I have the most recent data from the db.

When exactly should I be using 'reload', or should I just disable caching altogether?

For example this line in one of my tests, won't work without the 'reload' bits:

assert_equal @fl1.reload.orig_price, @fl1.lesson.reload.price #price is reset in previous

I'm starting to lose faith in passing tests because of this as well, thinking, yeah开发者_JAVA百科, but what if it's passing because of stale values.

Can anyone shed some light on this?


Basically, if you're working just in memory, you don't need to use reload. If you're going straight to the database, you will need to.

So, in general, something like:

@user = User.create!(:name => "John Doe", :age => 100, :login => "jdoe")
assert_equal "John Doe", @user.name

That will work just fine because everything about that object is in memory.

Now, let's say you did something like:

@user.pictures << Picture.create!(:locn => "/images/my_image.jpg")
assert @user.contains_picture(/images/"my_image.jpg")

and that method, contains_picture, was defined in user.rb as:

def contains_picture(path)
    User.includes(:picture).where("pictures.locn = ?", path)
end

Because that method goes directly to the database, it will fail because it will not find that picture. Instead, after adding the picture to the .pictures collection, you would need to do @user.save!

So, it depends on what is happening to the object and what the methods being used look like, and that will tell you if you need reloador not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜