Ruby on rails Rails:当存在固定装置时,使用FactoryGirl测试类方法

Ruby on rails Rails:当存在固定装置时,使用FactoryGirl测试类方法,ruby-on-rails,unit-testing,factory-bot,Ruby On Rails,Unit Testing,Factory Bot,我想测试以下模型的类方法: class Subscription < ActiveRecord::Base # ... self.active_within_timeframe(t1, t2) # method code end end 在我的应用程序中,我也有订阅装置。如何仅对FactoryGirl创建的记录运行测试 有没有办法在下面的测试中填写缺失的部分 class UserTest < ActiveSupport::TestCase test "s

我想测试以下模型的类方法:

class Subscription < ActiveRecord::Base
  # ...

  self.active_within_timeframe(t1, t2)
    # method code
  end
end
在我的应用程序中,我也有订阅装置。如何仅对FactoryGirl创建的记录运行测试

有没有办法在下面的测试中填写缺失的部分

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
classusertest
我想说使用或不使用固定装置。别把它混在一起。您可以将s1和s2添加到装置中。否则,不要在整个测试过程中加载夹具和使用工厂。我只使用fixture来填充开发环境中的DB和测试中的工厂。请参见本主题。此外,出于性能原因,您应该考虑使用非持久性(或甚至)对象,这是工厂在测试中优于夹具的另一个优点。
除了测试问题,我认为您应该使用a而不是class方法

您需要将其称为
订阅。在\u时间范围内激活\u
,您是在从FactoryGirl返回的实例上调用它。也许我不太清楚。我将fixture中的数据加载到subscriptions表中,这就是为什么我不在订阅上运行该方法的原因。谢谢你回答我的问题。现在,我想创建ActiveRecord::Relation类的subscriptions对象,并用FactoryGirl创建的对象加载它。为了强调这一点,我刚刚对代码做了一个小的修改。当然,我对其他的解决方案持开放态度。回答很好,谢谢。我想这正是我应该做的——要么只使用工厂,要么只使用固定装置。也谢谢你的文章。是的,如果我的取景器是一条直线,我肯定会选择使用示波器。。。
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