如何存根:当rspec测试使用respond_with的控制器时,错误集合无效

Chr*_*eck 6 rspec-rails ruby-on-rails-3

我重构了我OrgController的使用respond_with,现在控制器规范脚手架失败了这条消息:

1) OrgsController POST create with invalid params re-renders the 'new' template
   Failure/Error: response.should render_template("new")
     expecting <"new"> but rendering with <"">
Run Code Online (Sandbox Code Playgroud)

规范看起来像这样:

it "re-renders the 'new' template" do
 Org.any_instance.stub(:save).and_return(false)
 post :create, {:org => {}}, valid_session
 response.should render_template("new")
end
Run Code Online (Sandbox Code Playgroud)

我已经读过我应该将:errors哈希存根以使其看起来像是一个错误.最好的方法是什么?

Den*_*nis 11

使用RS3在v3中引入的新语法,存根看起来像

allow_any_instance_of(Org).to receive(:save).and_return(false)
allow_any_instance_of(Org).to receive_message_chain(:errors, :full_messages)
  .and_return(["Error 1", "Error 2"])
Run Code Online (Sandbox Code Playgroud)

相关的控制器代码看起来像

if org.save
  head :ok
else
  render json: {
    message: "Validation failed",
    errors: org.errors.full_messages
  }, status: :unprocessable_entity # 422
end
Run Code Online (Sandbox Code Playgroud)


mfa*_*kas 5

消息:

expecting <"new"> but rendering with <"">
Run Code Online (Sandbox Code Playgroud)

表明这是重定向而不是渲染。要么您的存根不成功,要么您的控制器位于控制器中。您应该能够测试存根是否适用于以下内容:Org.first.valid?Org.new(valid_attibutes).valid?。例如,如果mocha您的 中有存根Gemfile,则存根将会被破坏,因为在这种情况下,存根any_instance将是一个mocha对象,并且 rspecstub将无法处理它。如果存根有效,您可以使用日志记录或调试器来调试控制器中发生的情况。

对于存根错误,您可以执行以下操作:

Org.any_instance.stub(:errors).and_return(ActiveModel::Errors.new(Org.new).tap {
  |e| e.add(:name,"cannot be nil")})
Run Code Online (Sandbox Code Playgroud)

或者,如果控制器仅使用,errors.full_messages那么您可以:

Org.any_instance.stub_chain("errors.full_messages").and_return(["error1","error2"])
Run Code Online (Sandbox Code Playgroud)


ari*_*uod 1

你应该存根有效吗?方法:

Org.any_instance.stubs(:valid?).and_return(false)
Run Code Online (Sandbox Code Playgroud)

那么你的对象将不会被保存,因为它是无效的