我在使用 Rspec 测试控制器的更新操作时遇到问题,我做错了什么?
我正在尝试在控制器上测试更新操作的失败分支,但测试时遇到问题。这就是我所拥有的,但最后失败了
describe "PUT 'article/:id'" do
.
.
.
describe "with invalid params" do
it "should find the article and return the object" do
Article.stub(:find).with("1").and_return(@article)
end
it "should update the article with new attributes" do
Article.stub(:update_attributes).and_return(false)
end
it "should render the edit form" do
response.should render_template("edit")
end
end
end
关于为什么最后一部分无法渲染模板有什么想法吗?
I am trying to test the failing branch of the update action on my controller but I am having trouble with the test. This is what I have and it fails on the last
describe "PUT 'article/:id'" do
.
.
.
describe "with invalid params" do
it "should find the article and return the object" do
Article.stub(:find).with("1").and_return(@article)
end
it "should update the article with new attributes" do
Article.stub(:update_attributes).and_return(false)
end
it "should render the edit form" do
response.should render_template("edit")
end
end
end
Any ideas as to why the last part fails to render the template?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您错误地分割了测试的各个部分。每个
it
调用实际上都是一个新示例,并且状态在每次调用之前/之后都会重置。你应该做的是:
通过这种方式,
@article
是预先设置好的(尽管如果你真的想要的话,你可以使用模拟的)并且对update
操作的请求以及它实际呈现edit
模板的断言都发生在一个示例中。You're splitting up the parts of your test incorrectly. Each
it
call is actually a new example and the state is reset before/after each one.What you should be doing is:
By doing it this way, the
@article
is set up before hand (although you could use a mock one if you really wanted to) and the request to theupdate
action and the assertion that it actually renders theedit
template all happen in the one example.对于 2018 年来到这里的人们,已经进行了一些更新(不是双关语)。在列出参数之前包含“params”很重要。此外,您应该使用expect而不是“should”,因为它在Rails 6.0中将被弃用。
For people who are coming here in 2018, some updates(pun not intended) have been made. It's important to include "params" before listing the params. Additionally, you should use expect and not "should" since it will be deprecated in Rails 6.0.