gpt4 book ai didi

ruby-on-rails-3 - 如何 stub :errors collection to act invalid when rspec tests a controller that uses respond_with

转载 作者:行者123 更新时间:2023-12-03 00:47:39 26 4
gpt4 key购买 nike

我重构了我的 OrgController 以使用 respond_with,现在 Controller 规范支架失败并显示以下消息:

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 哈希进行 stub 处理,使其看起来像是存在错误。最好的方法是什么?

最佳答案

使用 RSpec 在 v3 中引入的新语法, stub 将如下所示

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"])

相关的 Controller 代码看起来像这样

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

关于ruby-on-rails-3 - 如何 stub :errors collection to act invalid when rspec tests a controller that uses respond_with,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11306559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com