我正在编写一个单元测试来检查24小时是否已经过去。如果24小时过去了,那么它应该返回真正的
这是我的
test "messenger tag is more than 24 hours" do
Timecop.travel 2.days.ago
account = accounts(:messenger_v2)
contact_d = Contact.create! account: account, name: 'Mr Right', phone_number: nil, external_id: '155581474881005', contact_type: 'MessengerV2', source: 'Inbound', is_registered: true, primary_contact: true
conversation = Conversation.create! contact: contact_d, account: account, status: 'Open', unread: true, conversation_type: 'Private'
Message.create! contact: contact_d, message_type: 'Text', text: 'I have some enquries', direction: 'IN', account: account, conversation: conversation, external_id: "in_a#{Time.now.to_i.to_s}"
msg = conversation.messages.incoming
time_created = msg.last.created_at
messenger_tags = time_created < 24.hours.ago
assert_equal true, messenger_tags
end
当我运行测试时,这里是输出
test_messenger_tag_is_more_than_24_hours FAIL (0.14s)
Expected: true
Actual: false
test/models/message_test.rb:175:in `block in <class:MessageTest>'
请协助
创建消息后,您需要使用Timecop.return
进行turn off Timecop
。
test "messenger tag is more than 24 hours" do
Timecop.travel 2.days.ago
account = accounts(:messenger_v2)
contact_d = Contact.create! account: account, name: 'Mr Right', phone_number: nil, external_id: '155581474881005', contact_type: 'MessengerV2', source: 'Inbound', is_registered: true, primary_contact: true
conversation = Conversation.create! contact: contact_d, account: account, status: 'Open', unread: true, conversation_type: 'Private'
Message.create! contact: contact_d, message_type: 'Text', text: 'I have some enquries', direction: 'IN', account: account, conversation: conversation, external_id: "in_a#{Time.now.to_i.to_s}"
Timecop.return
msg = conversation.messages.incoming
time_created = msg.last.created_at
messenger_tags = time_created < 24.hours.ago
assert_equal true, messenger_tags
end
更新或者您可以阻止到Timecop.travel
,以避免调用@Stefan在下面的评论中提到的Timecop.return
test "messenger tag is more than 24 hours" do
Timecop.travel 2.days.ago do
account = accounts(:messenger_v2)
contact_d = Contact.create! account: account, name: 'Mr Right', phone_number: nil, external_id: '155581474881005', contact_type: 'MessengerV2', source: 'Inbound', is_registered: true, primary_contact: true
conversation = Conversation.create! contact: contact_d, account: account, status: 'Open', unread: true, conversation_type: 'Private'
Message.create! contact: contact_d, message_type: 'Text', text: 'I have some enquries', direction: 'IN', account: account, conversation: conversation, external_id: "in_a#{Time.now.to_i.to_s}"
msg = conversation.messages.incoming
@time_created = msg.last.created_at
end
messenger_tags = @time_created < 24.hours.ago
assert_equal true, messenger_tags
end