Rspec验证测试在'put'更新时失败

时间:2012-12-08 01:47:26

标签: ruby ruby-on-rails-3 rspec factory-bot

我有这个工厂:@host = FactoryGirl.create(:host)

此测试通过:

it 'should update and redirect to the show page' do                                  
  new_attr = @host.attributes.merge("hostname" => "New_name")             
  put 'update', id: @host, host: new_attr              
  response.should redirect_to(host_path(@host))                           
end¬   

但是这个失败了:

  it 'should fail on validation for empty hostname and redirect to edit' do                                           
    bad_attr = @host.attributes.merge("hostname" => "")                     
    put 'update', id: @host, host: bad_attr                                 
    response.should redirect_to(edit_host_path(@host))                
  end 

出现此错误:

   1) HostsController POST update failure should redirect to edit
         Failure/Error: response.should redirect_to(edit_host_path(@host))
           Expected response to be a redirect to <http://test.host/hosts/1/edit> but was a redirect to <http://test.host/hosts/1>
         # ./spec/controllers/hosts_controller_spec.rb:127:in `block (4 levels) in <top (required)>'

在我的HostsController的#update中,使用空主机名验证失败的主机对象应该是redirect_to edit_host_path(@host)。这是我的HostsController#update

def update                                                                    
  @host = Host.find(params[:id])                                              
  if @host.save                 
    flash[:notice] = 'Host was successfully updated.'                         
    redirect_to host_path(@host)                                              
  else¬                                                                        
    redirect_to edit_host_path(@host)    
  end
end            

我在控制台中使用保存和更新属性,我的验证工作正常。那么为什么这个错误?有任何想法吗? Rspec似乎在说我的工厂对象具有错误的属性正在通过验证,但我的模型验证很好。谢谢。

1 个答案:

答案 0 :(得分:1)

/我做了一个脸庞。

在HostsController#update中,这个:

@host = Host.find(params[:id])
@host.save

应该是这样的:

@host = Host.find(params[:id])
@host.update_attributes(params[:host])