RSpec2测试模拟模型返回0个项目和没有响应正文

RSpec2测试模拟模型返回0个项目和没有响应正文

问题描述:

我试图创建一个API与Rails使用BDPC与RSpec。 Rails版本是3.1.1,Ruby版本是1.9.2,Devise版本是1.5.3,rspec版本是2.7.0。我对Rails比较陌生,对RSpec很新。RSpec2测试模拟模型返回0个项目和没有响应正文

我已经定义了一个简单的RSpec,如下测试一个基本上没有逻辑的FormsController。

describe FormsController, " handling GET /forms" do 
    include Devise::TestHelpers 
    render_views 

    before do   
    user = Factory.create(:user) # Handle Devise authentication 
    user.confirm! 
    sign_in user 

    @form = mock_model(Form) 
    Form.stub!(:all).and_return([ @form ]) 
    end 

    it "gets successfully" do 
    get :index, :format => :json 
    response.should be_success 
    end 

    it "finds all forms" do 
    Form.should_receive(:all).and_return([@form]) 
    get :index, :format => :json 
    Rails.logger.info "*** response.body="+response.body 
    end 
end 

当前表单控制器代码非常简单。

class FormsController < ApplicationController 
    before_filter :authenticate_user! 

    # GET /forms 
    # GET /forms.json 
    def index 
    @forms = Form.find_all_by_owner_id(current_user.id) 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render :json => @forms } 
    end 
    end 
end 

当我运行规范 “发现一切形式的” 总是失败,

Failure/Error: Form.should_receive(:all).and_return([@form]) 
    (<Form(id: integer, title: string, owner_id: integer, created_at: datetime, updated_at: datetime) (class)>).all(any args) 
     expected: 1 time 
     received: 0 times 

从日志输出/ test.log中显示:

*** response.body=[] 

为什么?我觉得这个问题源于Form.stub!(:all).and_return([ @form ]),但我不知道如何调试。

在此先感谢。

经过更多的试验和错误,以下解决方案为我工作。

  • 我从嘲笑表单模型使用工厂女孩打造完整的模型
  • 然后我更新了测试中使用的to_json来比较模型的响应迁移。

规格如下。

describe FormsController, " handling GET /forms" do 
    include Devise::TestHelpers 
    render_views 

    before do   
    user = Factory.create(:user) # Handle Devise authentication 
    user.confirm! 
    sign_in user 

    @form1 = Factory.create(:form) 
    end 

    it "gets successfully" do 
    get :index, :format => :json 
    response.should be_success 
    end 

    it "finds all forms" do 
    get :index, :format => :json 
    response.body.should == [ @form1 ].to_json 
    Rails.logger.info "*** response.body="+response.body 
    end 
end 

这将有助于张贴您的控制器代码(正在测试)。该错误说明声明Form.should_receive(:all).and_return([@form])尚未得到满足。声明说你应该在你的控制器的动作中有这样的代码:Form.all

find_all_by_owner_idForm.all不一样。 find_all_by_owner_id结束了做

Form.where(...).all 

它不符合您设定的期望。在你的具体情况下,我会告诉should_receive,我期待拨打find_all_by_owner_id而不是all

+0

我尝试这样做:'Form.should_receive(:find_all_by_owner_id).and_return([@形式])',但我得到:'故障/错误:得到:索引,:格式=>:JSON的ActiveSupport: :JSON :: Encoding :: CircularReferenceError:对象在它的两个块中引用自身。 – 2011-12-28 13:26:18

+0

我试着在你的模拟模型对象上写出'to_json'。 – 2011-12-28 18:28:54

+0

是的,我想这会起作用,但增加了很多复杂性。我最终使用Factory来创建我的Form。 – 2011-12-30 23:33:17