2013-03-26 105 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的回答,希望我的其他答案很有用!