I'd like to test a class method for the following model:
class Subscription < ActiveRecord::Base
# ...
self.active_within_timeframe(t1, t2)
# method code
end
end
Here are the factories:
FactoryGirl.define do
factory :subscription do
user_id 1
factory :s1 do
beginning 3.days.ago
ending 2.days.ago
end
factory :s2 do
beginning 1.day.ago
ending nil
end
end
end
In my application I also have fixtures for subscriptions. How can I run tests only against records created by FactoryGirl?
Is there a way to fill out the missing part in the test below?
class UserTest < ActiveSupport::TestCase
test "should find records for the given time frame" do
s1 = FactoryGirl.create(:s1)
s2 = FactoryGirl.create(:s2)
# Create an object (of e.g. ActiveRecord::Relation class) containing
# factories s1 and s2, and nothing from fixtures
# subscriptions = ...
records = subscriptions.active_within_timeframe(2.5.days.ago, 0.5.days.ago)
assert records.order('id desc') == [s1, s2].order('id desc')
end
end
I'd say use fixtures or don't. Don't mix it. You could just add your s1 and s2 to the fixtures. Otherwise just, don't load fixtures and use factories throughout your tests. I use fixtures only to populate the DB in my development env and factories in testing. See this article on the topic. Also for performance reasons, you should consider to use non-persisted (or even stubbed) objects where possbile, which is another advantage of factories over fixtures in testing.
Aside from the testing matter, I think you should use a scope instead of a class method