2015-10-06 18 views
1

我正在使用活動記錄update方法來更新多個記錄,每個記錄具有各自的屬性。Rails/AR - 如何在rspec中測試:: update(id,attributes)

我方便與此控制器代碼(工作):

def update 
    keys = params[:schedules].keys 
    values = params[:schedules].values 
    if Schedule.update(keys, values) 
    flash[:notice] = "Schedules were successfully updated." 
    else 
    flash[:error] = "Unable to update some schedules." 
    end 
    respond_to do |format| 
    format.html { redirect_to responsibilities_path } 
    end 
end 

我的問題是,我怎麼能測試,如果沒有擊中RSpec的數據庫?

這是我正在嘗試,但它不工作。

describe "PATCH update" do 

    it "updates the passed in responsibilities" do 
    allow(Schedule) 
     .to receive(:update) 
     .with(["1", "2"], [{"status"=>"2"}, {"status"=>"1"}]) 
     .and_return(true) 
    # results in 
    # expected: 1 time with arguments: (["1", "2"], [{"status"=>"2"}, {"status"=>"1"}]) 
    # received: 0 times 
    # Couldn't find Schedule with 'id'=1 

    # without the allow, I get 
    # Failure/Error: patch :update, schedules: { 
    # ActiveRecord::RecordNotFound: 
    # Couldn't find Schedule with 'id'=1 
    # # ./app/controllers/responsibilities_controller.rb:18:in `update' 
    # # ./lib/authenticated_system.rb:75:in `catch_unauthorized' 
    # # ./spec/controllers/responsibilities_controller_spec.rb:59:in `block (5 levels) in <top (required)>' 

    patch :update, schedules: { 
     "1" => { 
     "status" => "2", 
     }, 
     "2" => { 
     "status" => "1", 
     } 
    } 
    expect(Schedule) 
     .to receive(:update) 
     .with(["1", "2"], [{"status"=>"2"}, {"status"=>"1"}]) 
    expect(flash[:error]).to eq(nil) 
    expect(flash[:notice]).not_to eq(nil) 
    end 
end 

我on Rails的4.2.4和RSpec 3.0.0

回答

2

你的問題是,你與

expect(Schedule) 
     .to receive(:update) 
     .with(["1", "2"], [{"status"=>"2"}, {"status"=>"1"}]) 
     .and_call_original  

調用打補丁方法後期待。

這意味着請求在斷言建立之前命中您的控制器。 爲了解決這個問題,只需在補丁調用之前放置expect(Schedule)調用,這也可以讓您擺脫allow(Schedule).to - call。

乾杯。

+0

謝謝你的評論。我也嘗試過,這樣可以避免上述錯誤,但它不允許我測試對象中的更改。例如,如果我想確認狀態更改並添加預期(schedule.reload.status).to eq(2)的斷言,則失敗。有沒有辦法在這裏維護? – yekta

+0

您可能需要使用「.and_call_original」方法來實現這一點。當你斷言方法調用時,該方法不必在那裏,那就是那種功能。這意味着如果你沒有這麼說,它就不會被召喚。更新我的答案以表明這一點。 – jfornoff

+0

哇...太容易了!謝謝!! – yekta