当rspec测试使用respond_with的控制器时,如何对:errors集合进行操作以使其无效

问题描述 投票:6回答:4

我将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 <"">

规格看起来像这样:

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

我已经读过,我应该对:errors哈希进行存根处理,以使其看起来像是有错误。最好的方法是什么?

ruby-on-rails-3 rspec-rails
4个回答
12
投票
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"])

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

if org.save
  head :ok
else
  render json: {
    message: "Validation failed",
    errors: org.errors.full_messages
  }, status: :unprocessable_entity # 422
end

4
投票
expecting <"new"> but rendering with <"">

建议这是重定向而不是渲染。您的存根操作不成功,或者您的控制器在控制器中,但失败了。您应该能够测试存根是否适用于以下内容:Org.first.valid?Org.new(valid_attibutes).valid?。例如,如果mocha中有Gemfile,则存根将被破坏,因为在这种情况下,any_instance将是mocha对象,而rspec stub将无法在其上使用。如果存根有效,则可以使用日志记录或调试器来调试控制器中发生的情况。

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

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

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

Org.any_instance.stub_chain("errors.full_messages").and_return(["error1","error2"])

0
投票
Org.any_instance.stubs(:valid?).and_return(false)

然后您的对象将被保存,因为它将无效


0
投票
allow_any_instance_of(ReportFile).to receive(:save!).and_raise( ActiveRecord::RecordInvalid, ReportFile.new.tap do |rf| rf.errors.add(:data_file_size, 'must be less than 100 Megabytes') end )
© www.soinside.com 2019 - 2024. All rights reserved.