2013-03-26 67 views
3

我使用FactoryGirl和Rspec作为我的测试框架。我有一个模型,它有validates_presence_of验证。基本Rspec的框架包括一个测试:Rspec测试必需参数

describe "with invalid params" do 
    it "assigns a newly created but unsaved disease as @disease" do 
    # Trigger the behavior that occurs when invalid params are submitted 
    Disease.any_instance.stub(:save).and_return(false) 
    post :create, :disease => {} 
    assigns(:disease).should be_a_new(Disease) 
    end 
end 

编辑: diseases_controller.rb

# POST /diseases 
# POST /diseases.xml 
def create 
    @disease = Disease.new(disease_params) 

    respond_to do |format| 
    if @disease.save 
     format.html { redirect_to(@disease, :notice => 'Disease was successfully created.') } 
     format.xml { render :xml => @disease, :status => :created, :location => @disease } 
    else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @disease.errors, :status => :unprocessable_entity } 
    end 
    end 
end 

private 
def disease_params 
    params.require(:disease).permit(:name, :omim_id, :description) 
end 

此测试不与我有多么应用程序的工作工作。而不是在一个不正确的返回后一种新的疾病,它会返回一个错误:

Required parameter missing: disease 

问题1:我不知道如何来看待正在使用RSpec做后返回了什么。 response对象在这种情况下似乎不会创建?印刷assigns(:disease)似乎不包含任何内容。我收到了我之前发布的错误消息,它提交了一个cURL帖子到空数据的正确URL(这是rspect帖子应该做的),但我不知道如何获取Rspec从发表声明。

问题2:我如何正确地测试应该发生的响应 - 它收到一条错误消息,指出缺少必需的参数?

编辑: 所以我的控制者似乎表明它应该呈现一种新的疾病,但测试失败。如果我尝试提交缺少网站上所需参数的疾病,则会发出一条闪烁的提示,指出“姓名不能为空”。我不确定如何在rspec中测试它。

编辑#2: 包含上面的代码。根据使用宝石的建议,在控制器底部定义了疾病_params。

谢谢!

+0

显示动作 – apneadiving 2013-03-26 20:08:43

+0

您在哪里定义'disease_params'? – apneadiving 2013-03-26 20:31:23

+0

似乎在这里失败'params.require(:疾病)',但我不知道为什么 – apneadiving 2013-03-26 21:08:45

回答

3

要回答问题1(“我不知道如何查看返回的信息与Rspec的职位”)......您可以在规范中使用“puts”语句(即在it区块内) 。例如,你可以尝试这样的事情:

describe "with invalid params" do 
    it "assigns a newly created but unsaved disease as @disease" do 
    # Trigger the behavior that occurs when invalid params are submitted 
    Disease.any_instance.stub(:save).and_return(false) 
    post :create, :disease => {} 
    puts :disease 
    assigns(:disease).should be_a_new(Disease) 
    end 
end 

这是一个有价值的调试工具。 RSpec运行时,输出将在终端的.s和Fs中。

对于问题2,我不太确定你在找什么,但我不知道你需要(或者应该)测试该无效疾病是否被指定为@disease。我倾向于按照以下样式对控制器规格进行仿真(取自Everyday Rails Testing with RSpec,这是我学习如何编写控制器规格的地方)。

POST创建规范例如:

context "with invalid attributes" do 
    it "does not save the new contact" do 
    expect{ 
     post :create, contact: Factory.attributes_for(:invalid_contact) 
    }.to_not change(Contact,:count) 
    end 

    it "re-renders the new method" do 
    post :create, contact: Factory.attributes_for(:invalid_contact) 
    response.should render_template :new 
    end 
end 
... 

你可能有更彻底地测试控制器的方法,我不知道原因。在这种情况下,请不要理会我对问题2的回答,希望我的其他答案很有用!