我正在写一个单元测试,以检查24小时是否已经通过。如果24小时过去了,那么它应该返回true。
这是我的尝试
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>'请协助
发布于 2020-11-09 06:45:34
创建消息后,需要使用turn off Timecop使用Timecop.return。
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
endhttps://stackoverflow.com/questions/64746620
复制相似问题