0

我正在尝试设置规范以正确运行我的嵌套资源。

这是我正在尝试正确设置的测试代码

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。

4

1 回答 1

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)

再次编辑:

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

于 2013-01-19T20:10:33.700 回答