2014-10-16 39 views
1

我正在使用Ruby on Rails構建基本應用程序測試電子郵件功能。對於任何使用.not_to的測試,我得到一個NoMethodError。這裏是Rspec的,通過本教程提供我下面:Ruby on Rails Rspec NoMethodError:未定義方法'not_to'

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

我懷疑這些線路上的代碼被解釋以不同的順序,以什麼樣的預期:

expect (FavoriteMailer) 
     .not_to receive(:new_comment) 

試試這個:

expect(FavoriteMailer).not_to receive(:new_comment) 

主要要注意的是這是一個好習慣Ruby不會在方法調用和參數的左括號之間留下空間(儘管這通常可以起作用,但最好避免像這樣出現的頭部劃傷)。

在這個例子中,這意味着刪除expect(FavoriteMailer)之間的空格。

+0

這是正確的答案。 – sevenseacat 2014-10-16 14:44:00

0

是不是正確的方法to_not代替not_to?

更新 改爲to_not和not_to其他方式。

+0

都將工作。 – sevenseacat 2014-10-16 14:43:00

相關問題