11

我正在为我的 Rails 控制器编写规范,这是我正在测试的操作:

def create
  @course = Course.new(params[:course])
  if @course.save then
    #flash[:notice] = 'Course Created'
    redirect_to courses_path
  else
    render :action => 'new', :status => 400
  end
end

这是验证它的规范:

describe "POST /courses [Good Input]" do

  it "should redirect to Courses index page after creation" do
    @course.stub!(:save).and_return(true)
    post :create
    response.should be_success
    response.should redirect_to(courses_path)
  end

end

我仍然从 RSpec 收到此错误:

'CoursesController POST /courses [良好输入]

创建后应重定向到课程索引页面'

失败的

预期重定向到“/课程”,没有重定向

任何想法为什么会发生这种情况?

解决了

正如rishavrastogi所说,应该 be_success期望 http 代码在 2xx 范围内,并且重定向属于 3xx 范围(实际上是它的 302)

断言需要更改为 => response.should be_redirect

尽管在这种情况下,检查响应是否为重定向然后检查重定向到特定页面是多余的,因此不再需要断言。

4

2 回答 2

5

我也不是 RSpec-er,但我想“response.should be_success”不应该存在,因为响应实际上是“HTTP 重定向”而不是“HTTP 成功”......所以尝试删除 response.should be_success

也改变

发布:创建

发布:创建,:课程 => {}
于 2009-03-16T09:12:25.407 回答
0

我不是 rspecer,但你必须做类似assigns(:course).stub!.... 规范中的实例变量与控制器中的实例变量不同,assigns因此您可以访问控制器的实例变量。

于 2009-03-15T16:50:14.083 回答