如何在没有 Rails 的情况下测试 ActiveRecord? [英] How to test ActiveRecord witout Rails?
问题描述
我有一个项目,我使用 ActiveRecord 在 sqlite db 文件中存储信息.我没有使用 Rails,而 AR 似乎完美地完成了这项工作.我的问题是如何在不影响数据库的情况下测试我的课程?我发现了一些可以解决问题的 gem(FactoryGirl、UnitRecord),但它们旨在与 Rails 配合使用.
I have a project in which I use ActiveRecord to store information in a sqlite db file. I'm not using Rails and AR seems to do the job perfectly. My question is how exactly to test my classes witout hitting the db? I found some gems that would to the trick (FactoryGirl, UnitRecord), but they are meant to work with Rails.
class News < ActiveRecord::Base
belongs_to :feed
def delete_old_news_if_necessary
# time_limit = Settings::time_limit
return if time_limit.zero?
News.destroy_all("date < #{time_limit}")
end
def delete_news_for_feed(feed_id)
News.destroy_all(:id => feed_id)
end
def news_for_feed(feed_id)
News.find(feed_id)
end
end
我读到我可以做一个列存根:
I read that i can do a column stub:
Column = ActiveRecord::ConnectionAdapters::Column
News.stubs(:columns).returns([Column.new(),...])
这是进行这些测试的正确方法吗?另外,什么时候最好有一个单独的数据库用于测试并创建它,运行测试,然后删除它?
Is this the right way to do these tests? Also, when is it better to have a separate db just for testing and to create it, run the tests, and the delete it?
推荐答案
如果你想避免在测试中遇到数据库,我可以推荐 摩卡 宝石.它既可以存根,也可以让您定义期望.
If you want to avoid hitting the db in tests I can recommend the mocha gem. It does stubs as well as it lets you define expectations.
关于何时最好使用测试数据库的问题:我想说,只要没有理由反对它.:)
Regarding your question on when it is better to use a test db: I would say, whenever there is no reason against it. :)
例如,您可以在测试中像这样模拟 News.find
:
For example, you can mock News.find
like this in a test:
def news_for_feed_test
# define your expectations:
news = News.new
News.expects(:find).with(1).returns(news)
# call the method to be tested:
News.new.news_for_feed(1)
end
同时确保 find
被调用一次.Mocha 可以为您做更多的事情.看看文档.顺便说一句,你的这些方法看起来应该是类方法,不是吗?
At the same time this makes sure, find
gets called exactly once. There are a lot more things Mocha can do for you. Take a look at the documentation. Btw., it looks like these methods of yours should be class methods, no?
这篇关于如何在没有 Rails 的情况下测试 ActiveRecord?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!