2013-01-19 41 views
0

我试图设置规范以正确运行我的嵌套资源。Rspec测试:为嵌套资源创建方法

这是测试代码,我想正确设置

it "redirects to the created unit" do 
    post :create, {:course_id => @course.id , :unit => valid_attributes} 
    response.should redirect_to(course_unit_path(@course, Unit.last)) 
end 

这本质上应该尽量创造“课程”嵌套资源“单位”。 不幸的是,我发现了以下错误上的所有POST DELETE和PUT测试

Failure/Error: post :create, {:course_id => @course.id , :unit => valid_attributes} 
NoMethodError: 
    undefined method `unit_url' for #<UnitsController:0x000000059f1000> 

这是有道理的,因为unit_url应该course_unit_url但它的RSpec的调用它...

我怎样才能让RSpec的选择正确的命名路径? 对于所有GET测试,我手工传递了:course_id。

回答

0

这是我做过什么:

it "redirects to the created unit" do 
    unit_id = "barry" 
    Unit.any_instance.should_receive(:save).and_return(true) 
    Unit.any_instance.stub(:id).and_return(unit_id) 
    post :create, {:course_id => @course.to_param , :unit => valid_attributes} 
    response.should redirect_to(course_unit_path(@course, unit_id)) 
end 

我决定,这个测试的关键是不在于它创造了一个新的模式和重定向,但简单地认为它重定向。我有另一个规范来确保它创建一个新模型。这种方法的另一个好处是它不会触及数据库,所以它应该运行得更快一点。

我希望有帮助。

编辑:

我也是刚发现我有这个在我的before :each节这可能是相关的:再次

Course.stub!(:find).and_return(@course) 

编辑:

在这种情况下,有控制器中正在进行违规呼叫的代码。根据下面的评论。

+0

不幸的是它不起作用:-(我得到相同的错误... – user1978591

+0

嗯。它适用于我。它是否仍然失败,如果你使用1而不是“巴里”?我想我也使用相当于course_unit_url而不是course_unit_path。这有什么区别吗? – Geoff

+0

是的,它仍然失败......请看看整个规范[http://pastebin.com/sczZYEz6],如果它可能有帮助。“ “login_admin”是一个控制器规格宏,使用设计器登录 – user1978591