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 回答