Rails rspec expecte()。to with:where和.first

时间:2018-01-17 16:44:45

标签: ruby-on-rails rspec automated-tests

我是Rails的初学者,但我需要重新编写旧测试。 问题是不知道如何做到这一点。 例如,如何编写销毁部分: News.where(:id => 123).first

expect(News).to receive(:where).with('123')..?

看" 它"应该销毁新闻"做"在测试中。

非常感谢如何改进此测试的任何想法!

以下是news_controller_spec.rb

的一部分
    it "should destroy news" do
      News.should_receive(:find).with('123').and_return(@model)
      @model.should_receive(:destroy).and_return(true)
      delete :destroy, :id => 123, :step => 1
      response.should redirect_to(news_index_path)
    end

这是新闻控制器

class NewsController < ApplicationController
  layout 'layouts/news'

  skip_before_filter :login_required, :only => [:show, :index]
  before_filter :require_admin, :except => [:show, :index]
  before_filter :load_model, :only => [:edit, :update, :show, :destroy]

  def destroy
    @news.destroy
    redirect_to(@news, :notice => I18n.t(:news_deleted))
  end

protected
  def load_model
    @news = News.where(:id => params[:id]).first
    if @news.nil?
      redirect_to(news_index_url)
    end
  end

private
  def user_params
    params.require(:news).permit! if params[:news] #(:title,:content,:language)
  end
end

1 个答案:

答案 0 :(得分:0)

基本上你必须嘲笑方法,期待它在实际实现中会收到的参数。在这种情况下,<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <div id="myOther" swipe="alert('you swiped ' + touch.swipeInfo.direction + ' on ' + this.id);"> Swipe here </div> <div id="presser" once press="alert('you long pressed');"> Long press here </div> <div id="outer"> Tap here <div id="inner1" tap="alert('you tapped the first inner div and it will bubble');"> Tap here </div> <div id="inner2" stopPropagation tap="alert('you tapped the second inner div and it doesnt bubble');"> Tap here </div> </div><body> <script src="https://unpkg.com/goodtap"></script> <script> var tap = goodtap.init(); tap.on(document.getElementById("outer"), "tap", (event, target, touch) => alert("you tapped " + target.id)); </script> </body> </html> 将收到一个散列,指定要加载的模型的ID。这将返回一个带有double的数组(因为你要调用第一个方法)。您现在可以期望在双重调用上调用where方法。

destroy

(不确定你是否需要模拟describe '#destroy' do let(:news) { double('news', nil?: false) } context 'when called with known id' do before do allow(News).to receive(:where).with(id: 123).and_return([news]) allow(news).to receive(:destroy) end it 'should destroy corresponding news entry' do delete :destroy, id: 123 expect(response).to redirect_to(news_index_path) expect(news).to have_received(:destroy) end end end 但是现在没有控制台来测试它)