Spork在我的Rails应用程序中导致未定义的方法错误?

Dav*_*ite 5 ruby rspec ruby-on-rails spork rspec2

我有一个标准的Rails 3.2应用程序,有一些奇怪的行为正在进行.

我可以在rspec spec/没有spork运行的情况下运行,所有测试都没有问题.

然后我点起spork并再次运行规格.这一次,每次接触我的邮件的测试都会失败并出现同样的错误:

Failures:

  1) InvitationsController GET accept with non-matching token should redirect to the root path
     Failure/Error: let!(:invitation) { Factory :invitation }
     NoMethodError:
       undefined method `invite' for InvitationMailer:Class
     # ./app/models/invitation.rb:29:in `send_email'
     # ./spec/controllers/invitations_controller_spec.rb:5:in `block (3 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)

然后,只是为了让它变得有点奇怪,我可以运行单独的目录或规格,无论是否运行spork,一切都没有问题.例如rspec spec/mailersrspec spec/models.

这是我被告知未定义的方法:

class InvitationMailer < ActionMailer::Base
  default from: APP_CONFIG[:default_from]

  def invite(invitation)
    @invitation = invitation

    mail(to: @invitation.recipient_email, subject: "the subject")
  end
end
Run Code Online (Sandbox Code Playgroud)

有什么想法会发生什么?

B S*_*ven 0

在花了一些时间调整 Spork 之后,我认为可以解决这个问题。

由于某种原因,Spork 没有加载 InvitationMailer 文件。因此,您可以做的一件事就是在Spork.each_run do块内需要它。

另外,这是我用来诊断 Spork 问题的过程:

  1. 将规范助手中的所有内容移动require 'spork'到块内部之外Spork.prefork do。确保没有错误。使用time看看有多快。
  2. 将一些代码移动到Spork.each_run do块中。
  3. 检查是否发生错误。用于time查看测试运行的速度。
  4. 看看是否出现错误。如果是这样,则将一些代码移回pre_fork.
  5. 不断移动东西,直到你弄清楚块中需要什么prefork以及它运行的速度有多快。

这个过程在RailsCast中有解释。