Ruby on Rails Rspec NoMethodError:未定义的方法' not_to'

时间:2014-10-16 14:00:10

标签: ruby-on-rails rspec nomethoderror

我正在使用Ruby on Rails构建基本应用程序中的电子邮件功能。对于我使用.not_to的任何测试,我得到NoM​​ethodError。这是我正在遵循的教程提供的Rspec:

require 'rails_helper'

describe Comment do
  include TestFactories

  describe "after_create" do

    before do
      @post = associated_post
      @user = authenticated_user
      @comment = Comment.new(body: "My comment", post: @post, user_id: 10000)
    end

    context "with user's permission" do

      it "send an email to users who have favorited the post" do
        @user.favorites.where(post: @post).create

        allow( FavoriteMailer )
          .to receive(:new_comment)
          .with(@user, @post, @comment)
          .and_return( double(deliver: true) )

        @comment.save
      end

      it "does not send emails to users who haven't" do
        expect ( FavoriteMailer )
          .not_to receive(:new_comment)

        @comment.save
      end
    end

    context "without permission" do
      before { @user.update_attribute(:email_favorites, false) }

      it "does not send emails, even to users who have favorited" do
        @user.favorites.where(post: @post).create

        expect ( FavoriteMailer )
          .not_to receive(:new_comment)

        @comment.save
      end
    end

  end
end

这是错误:

Failures:

  1) Comment after_create with user's permission does not send emails to users who haven't
     Failure/Error: expect ( FavoriteMailer )
     NoMethodError:
       undefined method `not_to' for FavoriteMailer:Class
     # /home/vagrant/.rvm/gems/ruby-2.0.0-p576/gems/actionmailer-4.0.10/lib/action_mailer/base.rb:482:in `method_missing'
     # ./spec/models/comment_spec.rb:28:in `block (4 levels) in <top (required)>'

  2) Comment after_create without permission does not send emails, even to users who have favorited
     Failure/Error: expect ( FavoriteMailer )
     NoMethodError:
       undefined method `not_to' for FavoriteMailer:Class
     # /home/vagrant/.rvm/gems/ruby-2.0.0-p576/gems/actionmailer-4.0.10/lib/action_mailer/base.rb:482:in `method_missing'
     # ./spec/models/comment_spec.rb:41:in `block (4 levels) in <top (required)>'

Finished in 4.66 seconds (files took 24.42 seconds to load)
3 examples, 2 failures

Failed examples:

rspec ./spec/models/comment_spec.rb:27 # Comment after_create with user's permission does not send emails to users who haven't
rspec ./spec/models/comment_spec.rb:38 # Comment after_create without permission does not send emails, even to users who have favorited

2 个答案:

答案 0 :(得分:2)

我怀疑这些行上的代码是按照与预期不同的顺序解释的:

expect ( FavoriteMailer )
      .not_to receive(:new_comment)

试试这个:

expect( FavoriteMailer ).not_to receive(:new_comment)

要注意的主要事情是Ruby中的一个很好的约定是不要在方法调用和参数的开始括号之间留一个空格(尽管这通常可以起作用,但最好避免像这种裁剪一样停止头脑破坏向上)。

在此示例中,这意味着删除expect( FavoriteMailer )之间的空格。

答案 1 :(得分:0)

不是正确的方法而不是not_to吗?

<强>更新 改为to_not而不是其他方式。