我将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
哈希进行存根处理,以使其看起来像是有错误。最好的方法是什么?
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
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"])
Org.any_instance.stubs(:valid?).and_return(false)
然后您的对象将被保存,因为它将无效
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
)