1

次のリクエスト仕様があります

it "updates an open time" do
  # Create an OpenTime
  open_time = OpenTime.create(:start_time => (Time.now + 2.hours), :end_time => (Time.now + 10.hours))
  # Build an open_time update param
  params = {:open_time => {:start_time => (Time.now + 5.hours)}}
  # Send param to open_times#update
  put open_time_path(open_time.id) , params
  # Check to see if OpenTime was updated
  open_time.should_receive(:update_attributes).with({:start_time => (Time.now + 5.hours)})
end

これが私のopen_timesコントローラーです

def update
  @open_time = OpenTime.find(params[:id])
  if @open_time.update_attributes(params[:open_time])
    flash[:success] = "Time updated."
    redirect_to @open_time
  else
    render 'edit'
  end
end 

テストは予期されたもので失敗しています: 1 受信: 0

4

2 に答える 2

1

を受け取るのはそのオブジェクトではなく、update_attributesによって返される新しいオブジェクトOpenTime.findです。したがって、 find がオブジェクトを返すことを確認する必要があります。

OpenTime.stub(:find).and_return(open_time)
open_time.should_receive(:update_attributes).with({:start_time => (Time.now + 5.hours)})

その後:

put open_time_path(open_time.id) , params

さらに、テストの最初に追加target_time = Time.now + 5.hoursし、その時間をパラメーターとマッチャーで使用します。

于 2013-03-07T22:08:48.397 に答える
1

kr1が気付いたように、コントローラーから呼び出されたときに OpenTime.find メソッドをスタブして、OpenTime のインスタンスを返す必要があります。テスト コードを次のように変更します。

it "updates an open time" do
  target_time = (Time.now + 5.hours)
  # Create an OpenTime
  open_time = OpenTime.create(:start_time => (Time.now + 2.hours), :end_time => (Time.now + 10.hours))

  # Build an open_time update param
  params = {:open_time => {:start_time => target_time}}

  # Stub OpenTime to return your instance
  OpenTime.stub(:find).and_return(open_time)

  # Set expectation on open_time to receive :update_attributes
  open_time.should_receive(:update_attributes).with({:start_time => target_time})

  # Send param to open_times#update
  put open_time_path(open_time.id) , params
end

ここで起こっているのは、OpenTime(open_time) のインスタンスを構築し、OpenTime クラスをスタブ化することで、「誰かが OpenTime クラスで find を呼び出した場合、find を実行せずに単に open_time(作成したばかりのインスタンス) を返す」ということです。次に、インスタンスが :update_attributes を受け取るように設定します。put open_time_path(open_time.id)を呼び出すと、コントローラの作成アクションがリクエストを処理し、 OpenTime.find(...) がインスタンス(open_time)を返し、それに対して :update_attribute を呼び出します。

それが理にかなっていることを願っています。

于 2013-03-07T23:09:21.293 に答える