【问题标题】:RSpec should redirect_to problemRSpec应该redirect_to问题
【发布时间】:2009-03-15 16:04:56
【问题描述】:

我正在为我的 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 所述,应该是_success 期望 http 代码在 2xx 范围内,并且重定向落入 3xx 范围内(实际上是 302)

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

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

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

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

    也要改

     发布:创建 

     post :create, :course => {} 

    【讨论】:

    • 我为什么要更改 post :create?
    • 实际上,在您想要传递实例变量的一些值之前可能不需要这样做,例如“post :create ,:course => {:title=> "something" }.." 等。使用验证时可能需要这样做
    • 好的。谢谢。我在嘲笑一切(比如 Course.new 和 Course.find)......所以我真的不需要那个,但无论如何这是一个好点
    【解决方案2】:

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

    【讨论】:

    • 对不起,我应该在前面的块中声明我做 Course.stub!(:new).and_return(@course) 这是我创建的一个虚拟对象...
    猜你喜欢
    • 2013-05-27
    • 2010-11-03
    • 2011-08-27
    • 2014-05-13
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多