2014-07-01 42 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語法。