2014-07-01 45 views
2

系统调用这是帮助模块:嘲讽/磕碰使用RSPEC

module SendingMailHelper 
    def send_mail(subject, body) 
    to_email_id = " [email protected]" 
    cc_email_id = "[email protected]" 
    html_message = %{<html><body>#{body}</body></html>} 
    flag=false 
    while(!flag) do 
     flag = system %{echo "#{html_message}" | mutt -e "set content_type=text/html" -s "#{subject}" #{cc_email_id} -- #{to_email_id}} 
    end 
    flag 
    end 
end 

我写我的规格的方式是如下,但它不工作:

require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') 

describe SendingMailHelper do 
    it "test something" do 
    html_message = %{<html><body>www.google.com</body></html>} 
    to_email_id = " [email protected]" 
    cc_email_id = "[email protected]" 
    subject = "test e-mail" 
    SendingMailHelper.expects(:system).with(%{echo "#{html_message}" | mutt -e "set content_type=text/html" -s "#{subject}" #{cc_email_id} -- #{to_email_id}}).returns(true).once 
    helper.send_mail("test e-mail","www.google.com").should==true 
    end 
end 

收到以下错误:

SendingMailHelper test something 
    Failure/Error: SendingMailHelper.expects(:system).with(%{echo "#{html_message}" | mutt -e "set content_type=text/html" -s "#{subject}" #{cc_email_id} -- #{to_email_id}}).returns(true).once 
    Mocha::ExpectationError: 
     not all expectations were satisfied 
     unsatisfied expectations: 
     - expected exactly once, not yet invoked: 

我也想嘲笑它以这样的方式嘲弄狗返回false两次,并在第三次调用中测试重试机制。有没有办法做到这一点?

+1

试试'Kernel.expects(:system)...' – BroiSatse

+0

我该如何解决上述测试案例? – user1280282

回答

0
require_relative './sending_mail_helper' 
require 'rspec/mocks/standalone' 

describe SendingMailHelper do 
    let(:helper) do 
    Class.new do 
     include SendingMailHelper 
     attr_reader :system_calls 

     def system(*args) 
     @system_calls ||= [] 
     @system_calls << args 
     [false, false, true][(@system_calls.size - 1) % 3] 
     end 
    end.new 
    end 

    it "test the call is made" do 
    html_message = %{<html><body>www.google.com</body></html>} 
    to_email_id = " [email protected]" 
    cc_email_id = "[email protected]" 
    subject = "test e-mail" 
    helper.send_mail("test e-mail","www.google.com") 
    # check it was called once 
    helper.system_calls.size should eq 1 
    # check it was called with appropriete arguments 
    helper.system_calls.last.first.should eq %{echo "#{html_message}" | mutt -e "set content_type=text/html" -s "#{subject}" #{cc_email_id} -- #{to_email_id}} 
    end 

    it "retries the command until it succeded" do 
    helper.send_mail("test e-mail","www.google.com") 
    helper.system_calls.size.should eq 3 
    end 
end 

你可以使用这个小黑客。实际上,这几乎是stub和mock所做的监视函数调用的方法。试图使用rspec-mock工具运行测试失败的很糟糕。特别是,我建议您不要测试系统调用,它实际上会在测试中带来很多耦合和实施,并使代码更难维护。另一个建议,我会给你使用一些红宝石宝石来处理你试图实现的电子邮件功能insted使用SYS调用commands.Finally使用shoulds,但我已老rspec gem在我的电脑上,并且缺少新的expect语法。