2011-05-09 102 views
1

我是rspec和inherited_resources的新手。我有一个简单的资源,联系人,它有一个名称字段。控制器没有特殊的功能。Rspec与inherited_resources重定向,而不是渲染失败更新

class ContactsController < InheritedResources::Base 
    actions :all, :except => [:show] 
end 

我写了使用mock_model创建和索引的规格很好。但是,在更新时使用mock_model时,它在放置时找不到联系人。所以,我转而使用真正的模型:

describe "PUT update" do 
let(:contact) { Contact.create(:name => "test 1") } 

it "edits the contact" do 
    contact.name = "#{contact.name}-edited" 
end 
context "when the contact updates successfully" do 
    before do 
    contact.stub(:save).and_return(true) 
    end 
    it "redirects to the Contacts index" do 
    put :update, :id => contact.id, :contact => contact 
    #assigns[:contact].name = "test 1 - edited" 
    response.should redirect_to(:action => "index") 
    end 
end 

context "when the contact fails to save" do 
    before do 
    contact.stub(:save).and_return(false) 
    contact.stub(:update_attributes).and_return(false) 
    contact.stub(:errors).and_return(:errors => { :anything => "anything" }) 
    end 
    it "renders the edit template" do 
    put :update, :id => contact.id, :contact => contact 
    response.should render_template :edit 
    end 
end 
end 

我得到以下错误:

Failures: 

    1) ContactsController PUT update when the contact fails to save renders the edit template 
    Failure/Error: response.should render_template :edit 
    Expected block to return true value. 
    # ./spec/controllers/contacts_controller_spec.rb:82:in `block (4 levels) in <top (required)>' 

当我检查STATUS_CODE,这是一个302重定向到/联系人/:ID。

我在做什么错?

回答

3

当人们开始在控制器测试中使用mock时,这是一个非常常见的问题。你在规范本地的对象上存根方法。当您使用put访问控制器时,InheritedResources调用Contact.find(params[:id])并获取其自己的对象,而不是您想要的对象。

您的规格失败,因为update_attributes运行正常且重定向回到对象的show页面。

此问题的一般修补程序也是模拟您的模型上的find方法,以便它返回您的废除对象而不是另一个。

Contact.should_receive(:find).and_return(contact) 
contact.should_receive(:update_attributes).and_return(false) 
put :update, :id => contact.id, # etc. 
+0

这一切都变得清晰。谢谢! – rmw 2011-05-11 16:37:48