使用rspec codechool 5级测试进行测试4

时间:2014-04-05 21:33:08

标签: ruby-on-rails ruby rspec

以下是测试的基本问题:

We've changed the code below so we're mocking ZombieMailer.tweet method instead of the entire method. There is still more to do to make this example work. First, finish the let(:mail) statement below by creating a stub with a deliver method that returns true.
Then update the mock so the call to the tweet method returns the mail stub you created. 

不幸的是我无法改变模型,问题或邮件。

型号:

# tweet.rb
class Tweet < ActiveRecord::Base
  belongs_to :zombie
  validates :message, presence: true
  attr_accessible :message

  after_create :email_tweeter

  def email_tweeter
    ZombieMailer.tweet(zombie, self).deliver
  end
  private :email_tweeter
end

# zombie.rb
class Zombie < ActiveRecord::Base
  has_many :tweets
  validates :email, presence: true
  attr_accessible :email
end

邮件程序:

class ZombieMailer < ActionMailer::Base
  def tweet(zombie, tweet)
    mail(:from => 'admin@codeschool.com',
         :to => zombie.email,
         :subject => tweet.message)
  end
end

我一直在这方面蹦蹦跳跳,可以使用一些指针。以下是我现在一直在使用的测试问题3.现在他们要求添加传递方法,但他的方法不存在,或者至少我没有把它放在正确的位置。

已更新

describe Tweet do
  context 'after create' do
    let(:zombie) { Zombie.create(email: 'anything@example.org') }
    let(:tweet) { zombie.tweets.new(message: 'Arrrrgggghhhh') }
    let(:mail) { stub(:deliver => true) }

    it 'calls "tweet" on the ZombieMailer' do
      ZombieMailer.should_receive(:tweet).returns(:mail)
      tweet.save
    end
  end
end

错误信息是:

Failures:

1) Tweet after create calls "tweet" on the ZombieMailer
Failure/Error: ZombieMailer.should_receive(:tweet).returns(:mail)
NoMethodError:
undefined method `returns' for #<RSpec::Mocks::MessageExpectation:0x0000000519ab90>
# zombie_spec.rb:8:in `block (3 levels) '

Finished in 0.37725 seconds
1 example, 1 failure

Failed examples:

rspec zombie_spec.rb:7 # Tweet after create calls "tweet" on the ZombieMailer

任何rspec偷看都可以指出我在这里错过了什么?谢谢。

1 个答案:

答案 0 :(得分:0)

感谢上述评论中的@Paritosh和@Alex,以下是最终答案。

describe Tweet do
  context 'after create' do
    let(:zombie) { Zombie.create(email: 'anything@example.org') }
    let(:tweet) { zombie.tweets.new(message: 'Arrrrgggghhhh') }
     let(:mail) { stub(:deliver => true) }

    it 'calls "tweet" on the ZombieMailer' do
      ZombieMailer.should_receive(:tweet).and_return(mail)
      tweet.save
    end
  end
end