2009-05-31 53 views
1

嘿,我完全失去了這一個。指定手動呼叫有效?

我在網上找到一個代碼片段,以幫助驗證通過ajax字段,因爲用戶鍵入他們。所以我試圖寫一個規範來反對它的一部分,我無法讓它通過。

下面的代碼

def validate 
    field = params[:field] 
    user = User.new(field => params[:value]) 
    output = "" 
    user.valid? 
    if user.errors[field] != nil 
    if user.errors[field].class == String 
     output = "#{field.titleize} #{user.errors[field]}" 
    else 
     output = "#{field.titleize} #{user.errors[field].to_sentence}" 
    end 
    end 
    render :text => output 
end 

,這裏是我的測試,到目前爲止

describe "POST validate" do 
    it "retrieves the user based on the past in username" do 
     mock_errors ||= mock("errors") 
     mock_errors.stub!(:[]).and_return(nil) 
     User.should_receive(:new).with({'username'=>"UserName"}).and_return(mock_user) 
     mock_user.should_receive(:valid?).and_return(true) 
     mock_errors.should_receive(:[]).with("username").and_return(nil) 
     put :validate, :field=>'username', :value=>'UserName'  
     response.should == "" 
    end 
    end 

我得到這個錯誤 -

1)規格::嘲笑:: MockExpectationError 在'UsersController POST驗證 根據我們過去的 檢索用戶ername」模擬‘錯誤’收到 意外的消息:[]與 (‘用戶名’)

我似乎無法弄清楚如何在世界嘲笑調用user.errors [場]。理想情況下,這個規範測試了快樂的道路,沒有錯誤。然後我會寫另一個驗證失敗。

回答

1

我沒有看到mock_user。這裏有一個鏡頭吧:

describe "POST validate" do 
    it "retrieves the user based on the past in username" do 
    mock_errors = mock("errors") 
    mock_user = mock("user") 
    mock_user.stub!(:errors).and_return([mock_errors]) 
    mock_errors.stub!(:[]).and_return(nil) 
    User.should_receive(:new).with({'username'=>"UserName"}).and_return(mock_user) 
    mock_user.should_receive(:valid?).and_return(true) 
    mock_errors.should_receive(:[]).with("username").and_return(ActiveRecord::Errors.new({})) 
    put :validate, :field=>'username', :value=>'UserName'  
    response.should == "" 
    end 
end 

的關鍵是,你需要你的用戶模擬到通過返回一個空散列或字段名/錯誤的散列以錯誤的方法作出迴應。另一種替代方法是使用夾具替換工具之一。我現在正在使用機械師,這可能會減少這整個事情:

describe "POST validate" do 
    it "retrieves the user based on the past in username" do 
    @user = User.make{'username'=>"UserName"} 
    @user.should_receive(:valid?).and_return(true) 
    @user.errors.should_receive(:[]).with("username").and_return(ActiveRecord::Errors.new({})) 
    put :validate, :field=>'username', :value=>'UserName'  
    response.should == "" 
    end 
end