Rails:我想存根 Time.now 但它不会在范围内存根
我有这样的范围,
scope :old, joins(:group).where("`users`.`created_at` <=
DATE_SUB(?, INTERVAL `groups`.`check_minutes` MINUTE)", Time.now)
我存根Time.now
,如下所示,
Time.stub!(:now).and_return(Time.parse("1 JUL 2010"))
我希望范围old
使用这个存根Time.now
,但它使用当前时间。
我认为rails在第一次加载模型时创建范围(例如加载spec_helper.rb时),所以我们在加载范围后存根Time.now。这是真的吗?
所以我找到了两个解决方案:
- 在存根 Time.now 之后和使用范围之前重新加载用户模型
- 使用常规方法而不是像这样的存根
您有更优雅的解决方案吗?
I have such scope
scope :old, joins(:group).where("`users`.`created_at` <=
DATE_SUB(?, INTERVAL `groups`.`check_minutes` MINUTE)", Time.now)
I stub Time.now
as following
Time.stub!(:now).and_return(Time.parse("1 JUL 2010"))
I want scope old
to use this stubbed Time.now
but it uses current time.
I suppose rails create scopes when load model first time (e.g. when load spec_helper.rb
), so we stub Time.now after loading the scope. Is it true?
So I found two solutions:
- Reload User model after stubbing Time.now and before using scope
- Use regular method instead of stub like this
Do you have more elegant solutions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在普通作用域中包含
Time.now
是不可取的,因为您声明作用域是在加载模型类时设置的,因此长时间运行的 Rails 进程可能具有几小时或几天前的作用域。存根问题是这种不良情况的副作用。我建议您使用
lambda
重写您的作用域,以便始终查询Time.now
。这将缓解存根问题并始终获得最新的Time.now
。我不太喜欢这里的 lambda 语法,但它确实可以完成这项工作。
Having
Time.now
in a plain scope is undesirable, as you state the scope is setup when the model class is loaded, so a long running Rails process may have a scope that is from hours or days ago. The stubbing issue is a side-effect of this undesirable situation.I would suggest you rewrite your scope using a
lambda
, so thatTime.now
is always queried. This will alleviate the stubbing issue and always get the latestTime.now
.I'm not a huge fan of the lambda syntax here, but it does do the job.