【问题标题】:Testing Rails 3 respond_with with RSpec使用 RSpec 测试 Rails 3 respond_with
【发布时间】:2011-08-15 19:31:22
【问题描述】:

我最近更改了我的控制器代码:

  def create
    @checklist_item = @checklist.items.build(params[:checklist_item])
    if @checklist_item.save
      flash[:notice] = "Successfully created checklist item."
      redirect_to checklist_item_url(@checklist, @checklist_item)
    else
      render :action => 'new'
    end
  end

  respond_to :html, :json
  def create
    @checklist_item = @checklist.items.build(params[:checklist_item])
    if @checklist_item.save
      flash[:notice] = "Successfully created checklist item."
    end
    respond_with @checklist_item
  end

但是我的规范与我以前的控制器代码配合得很好,但失败了:

  it "create action should render new template when model is invalid" do
    checklist_item.stub(:valid? => false)
    checklist.stub_chain(:items, :build => checklist_item)
    post :create, :checklist_id => checklist.id
    response.should render_template(:new)
  end

出现错误:

1) Checklists::ItemsController create action should render new template when model is invalid
     Failure/Error: response.should render_template(:new)
     MiniTest::Assertion:
       Expected block to return true value.

我不确定如何更改规格。当我在浏览器中测试它时,一切功能仍然相同(它呈现新的)。

【问题讨论】:

  • 奇怪的是它不渲染节目。你确定它是新的吗?
  • 目标是渲染 :new 因为模型无效。通过有效模型的另一个测试工作正常,并且重定向显示没有问题。

标签: ruby-on-rails ruby-on-rails-3 rspec rspec2


【解决方案1】:

很有趣,刚刚尝试过,确实response 包含的内容不多。

只是状态 302。测试:response.status.should eq 302

身体像:

"<html><body>You are being <a href=\"new_url">redirected</a>.</body></html>"

这也很容易测试。

我会进一步挖掘。


编辑:

即使使用render_viewsresponse 仍然只是一个重定向。

您还可以查看response.header,它看起来像:

{"Location"=>"http://test.host/users", "Content-Type"=>"text/html; charset=utf-8"}

【讨论】:

  • 可能是身份验证将您重定向到登录页面吗?
【解决方案2】:

原因是 responds_with 检查 .errors.empty? 而不是 valid?(我想它不想不必要地重新运行验证)。所以我猜是把.errors删掉了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多