Rails 4 Action Mailer Previews和Factory Girl问题

时间:2015-08-20 12:45:01

标签: ruby-on-rails-4 factory-bot actionmailer

在处理Rails 4动作邮件预览和工厂女孩时,我遇到了一个非常烦人的问题。这是我的一些代码的示例:

class TransactionMailerPreview < ActionMailer::Preview
  def purchase_receipt
    account = FactoryGirl.build_stubbed(:account)
    user = account.owner
    transaction = FactoryGirl.build_stubbed(:transaction, account: account, user: user)
    TransactionMailer.purchase_receipt(transaction)
  end
end

这可能是任何动作邮件预览。让我说我得到了一些错误(每次都发生),并且出现了错误。我修复了错误并刷新了页面。每次发生这种情况我都会得到:

&#34; Rails :: MailersController#preview中的ArgumentError 用户的副本已从模块树中删除但仍处于活动状态!&#34;

然后我唯一的出路就是重启我的服务器。

我在这里遗漏了什么吗?有关导致这种情况的原因以及如何避免这种情况的任何线索?由于这个原因,我在过去一周内重启了我的服务器100次。

编辑:在我编辑代码并刷新预览的任何时候,实际上可能会发生这种情况吗?

2 个答案:

答案 0 :(得分:0)

虽然这不是一个答案(但也许是一个线索),我也有这个问题。

您的工厂是否会导致任何记录实际持续存在?

我最终在可能的地方使用Factory.build,并使用私有方法和OpenStructs删除所有其他内容,以确保每次重新加载时都创建了所有对象,并且没有任何内容可以继续重新加载。

我想知道FactoryGirl.build_stubbed使用什么来诱骗系统认为对象被持久化导致系统尝试重新加载它们(在它们消失后)。

这里有一段对我有用的内容:

class SiteMailerPreview < ActionMailer::Preview

  def add_comment_to_page
    page = FactoryGirl.build :page, id: 30, site: cool_site
    user = FactoryGirl.build :user
    comment = FactoryGirl.build :comment, commentable: page, user: user
    SiteMailer.comment_added(comment)
  end

  private

  # this works across reloads where `Factory.build :site` would throw the error: 
  # A copy of Site has been removed from the module tree but is still active!
  def cool_site
    site = FactoryGirl.build :site, name: 'Super cool site'
    def site.users
      user = OpenStruct.new(email: 'recipient@example.com')
      def user.settings(sym)
        OpenStruct.new(comments: true)
      end
      [user]
    end
    site
  end

end

虽然我对这种方法并不完全满意,但我不会再犯这些错误了。

我很想知道其他人是否有更好的解决方案。

答案 1 :(得分:0)

这回答了我的问题:

https://stackoverflow.com/a/29710188/2202674

我使用了方法3:只需将::放在违规模块的前面即可。