簡體   English   中英

在rails和rspec API上使用mock和stub

[英]Using mock's and stubs over rails and rspec API

我的問題更多的是一般性質。 在處理不同類型的代碼時,我已經對控制器進行了rspec測試,其中一些代碼使用rails和rspec API,而其他代碼使用mock和stubbing,我開始思考。

我想到的是什么是使用模擬的和存根在建軌道和RSpec API測試控制器 ,如果有人能解釋一下哪種方法更好腦橋缺點

一般來說,他們可以做同樣的事情(至少在某一點上)。 除了代碼的外觀或使測試更具表現力之外的其他區別,

如果你的問題是關於為什么要模擬和存根,那么沒有簡短的答案。 這些任務使測試變得更加容易,因為它允許您在測試期間更好地控制軟件的行為。 通過這種方式,測試變得更快,更簡單,更“單一”。

例如,在控制器中的create操作中,您可能希望在保存模型時測試其行為。 如果你不是存根,你需要創建兩個不同的實例; 一個是有效的,另一個不是。

it "redirects to message with a notice on successful save" do
  message_params = FactoryGirl.attributes_for(:message)
  post :create, message_params
  flash[:notice].should_not be_nil
  response.should redirect_to(Message.last)
end
it "renders a :new template with a notice on unsuccessful save" do
  message_params = FactoryGirl.attributes_for(:message, name: nil)
  post :create, message_params
  flash[:notice].should_not be_nil
  response.should render_template :new
end

如您所見,有必要創建兩個Message實例; 一個有效,一個無效。 我們必須使用FactoryGirl來創建它們。 換句話說,測試不是完全單一的,因為在創建實例時其他事情可能會出錯。 我們真正想測試的是:如果保存成功,它會重定向到第X頁嗎? 所以我們只想確保@message.valid? 在一種情況下返回true在另一種情況下返回false 這可以使用存根輕松完成:

it "should redirect to message with a notice on successful save" do
  Message.any_instance.stubs(:valid?).returns(true)
  post 'create'
  flash[:notice].should_not be_nil
  response.should redirect_to(Batch.last)
end
it "should render new template with a notice on unsuccessful save" do
  Message.any_instance.stubs(:valid?).returns(false)
  post 'create'
  flash[:notice].should be_nil
  response.should render_template('new')
end    

因此,在這種情況下,測試要輕得多,因為我們不必創建對象的實例,我們只是將方法存根以返回我們想要返回的內容。 使用它還有很多其他原因,你可以學習更多關於模擬和存根的閱讀。

但是,如果您的問題是,使用Rspec的內置模擬和存根功能,或使用外部寶石,如Mocha,那么答案就更短了:今天,我相信它更多的是個人偏好。 在過去,像Mocha這樣的框架具有any_instance沒有的功能,例如上面使用的any_instance方法。 但Rspec進化了,今天它和其他人一樣好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM