问题
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?
回答1:
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.
Edit: Regarding your question on when it is better to use a test db: I would say, whenever there is no reason against it. :)
Edit: 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
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?
来源:https://stackoverflow.com/questions/14750959/how-to-test-activerecord-witout-rails