【发布时间】:2013-09-25 04:31:18
【问题描述】:
我正在编写一个应用程序,允许用户相互发送有关“优惠”的消息。
我想我可以节省一些工作并使用 Mailboxer gem。
我正在使用 RSpec 遵循测试驱动的开发方法。我正在编写一个测试,以确保每个报价只允许一个Conversation。一个报价belongs_to 两个不同的用户(提出报价的用户和收到报价的用户)。
这是我失败的测试:
describe "after a message is sent to the same user twice" do
before do
2.times { sending_user.message_user_regarding_offer! offer, receiving_user, random_string }
end
specify { sending_user.mailbox.conversations.count.should == 1 }
end
所以在测试运行之前,用户sending_user 向接收用户发送了两次消息。 message_user_regarding_offer! 看起来像这样:
def message_user_regarding_offer! offer, receiver, body
conversation = offer.conversation
if conversation.nil?
self.send_message(receiver, body, offer.conversation_subject)
else
self.reply_to_conversation(conversation, body)
# I put a binding.pry here to examine in console
end
offer.create_activity key: PublicActivityKeys.message_received, owner: self, recipient: receiver
end
在测试的第一次迭代中(发送第一条消息时)conversation 变量为nil,因此发送了一条消息并在两个用户之间创建了对话。
在第二次迭代中,返回第一次迭代中创建的对话,用户回复该对话,但没有创建新对话。
这一切正常,但测试失败,我不明白为什么!
当我在上面指定位置的代码中放置一个 pry 绑定时,我可以检查发生了什么......现在让我猜一下:
self.mailbox.conversations[0] 返回一个Conversation 实例
self.mailbox.conversations[1] 返回nil
self.mailbox.conversations 清楚地显示了一个包含 ONE 对象的集合。
self.mailbox.conversations.count 返回 2?!
那里发生了什么? count 方法不正确,我的测试失败了...
我错过了什么?或者这是一个错误?!
编辑
offer.conversation 看起来像这样:
def conversation
Conversation.where({subject: conversation_subject}).last
end
和offer.conversation_subject:
def conversation_subject
"offer-#{self.id}"
end
EDIT 2 - 在 pry 中显示第一次和第二次迭代
还有……
Conversation.all.count 返回 1!
和:
Conversation.all == self.mailbox.conversations 返回true
和
Conversation.all.count == self.mailbox.conversations.count 返回false
如果数组相等怎么办?我不知道这里发生了什么,现在已经花了好几个小时了。认为这是一个错误?!
编辑 3
来自 Mailboxer gem 的来源...
def conversations(options = {})
conv = Conversation.participant(@messageable)
if options[:mailbox_type].present?
case options[:mailbox_type]
when 'inbox'
conv = Conversation.inbox(@messageable)
when 'sentbox'
conv = Conversation.sentbox(@messageable)
when 'trash'
conv = Conversation.trash(@messageable)
when 'not_trash'
conv = Conversation.not_trash(@messageable)
end
end
if (options.has_key?(:read) && options[:read]==false) || (options.has_key?(:unread) && options[:unread]==true)
conv = conv.unread(@messageable)
end
conv
end
reply_to_convesation 代码可在此处获得 -> http://rubydoc.info/gems/mailboxer/frames。
只是看不出我做错了什么!可能会修改我的测试来解决这个问题。或者放弃 gem 并编写我自己的。
【问题讨论】:
-
您的
self.mailbox.conversations是否类似于[conversation_instance, nil]? -
不,里面没有 nil 对象
-
我错过了什么吗?我看到
2.times,但期望count == 1。 -
我有一个非常相似的问题。计数更新程序直接进入数据库而不更改活动记录。在包含计数的记录上使用
reload修复它。 -
reply_to_conversation是做什么的?我很想看看代码。是否有可能在数据库中创建另一个对话?
标签: ruby-on-rails ruby activerecord rspec mailboxer