ruby-on-rails - Rails respond_with & Rspec Controller : Testing unsuccessful update

标签 ruby-on-rails rspec respond-with

我正在尝试在 Rails Controller 中从使用 respond_to 切换到 respond_with。一切都很顺利,除了测试 Controller 规范中的无效保存。下面是一个例子:

描述 MyController 做
...

describe "PUT update" do
    context "with invalid attributes" do
      it "should re-render the edit page" do
        style = stub_model(Style)
        Style.stub(:find) { style } 
        Style.any_instance.stub(:save).and_return(false)
        put :update
        response.should render_template(:edit)
      end
    end
  end
end

这适用于我旧的 response_to 样式更新操作,但使用 response_with,我得到

Failure/Error: response.should render_template("edit")



所以,简而言之 - 我该如何测试? ...或者我应该假设 render_with 知道它在做什么而根本不测试?有什么一般建议吗?

提前干杯

PS:更新 Action :
  def update
    @style = Style.find(params[:id])
    flash[:notice] = "Style updated" if @style.update_attributes(params[:style])
    respond_with(@style)
  end

最佳答案

我一直在研究这个确切的事情(我是如何找到这个话题的) - 到目前为止,我有以下几点:

Location.any_instance.stub(:valid?).and_return(false)
Location.any_instance.stub(:errors).and_return('anything')

(其中 Location 是我使用 response_with 的模型)

但是我相信一定有更好的方法来做到这一点 - 如果我找到它,我一定会发布它!

注意:我也在使用响应者 gem,因此如果您不使用这些行之一,您可能不需要它!

关于ruby-on-rails - Rails respond_with & Rspec Controller : Testing unsuccessful update,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10215156/

相关文章:

ruby-on-rails - JSON、response_with 和嵌套资源路由错误?

javascript - 如果没有内容,如何隐藏 Bootstrap 警报?

ruby-on-rails - Rails 应用程序因超时而崩溃

ruby - 模型中的 RSpec 模拟或 stub super

ruby-on-rails - 用于构建新操作的 rspec 匹配器

ruby-on-rails - rails 3 : Proper way to Delete resource using respond_with

ruby-on-rails - 无法安装 gem pg - 找不到 PostgreSQL 客户端库 (libpq)

ruby-on-rails - ldap 设备中的多个组可验证

ruby-on-rails - 在 View 规范中测试 "dynamic"页面标题 (Rails 4 + RSpec 3)