我在使用Rspec测试控制器的更新操作时遇到问题,我在做什么错? [英] I am having trouble testing my controller's update action using Rspec, what am I doing wrong?
问题描述
我正在尝试在控制器上测试更新操作的失败分支,但测试遇到问题.这就是我所拥有的,最后一次失败了
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?
推荐答案
您不正确地分割了测试的各个部分.每次it
调用实际上都是一个新示例,并且在每次调用之前/之后都将重置状态.
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.
您应该做的是:
describe "with invalid params" do
before do
@article = Article.create(valid_params_go_here)
end
it "should find the article and return the object" do
put :update, { :id => @article.id, :article => { :title => "" } }
response.should render_template("edit")
end
end
通过这种方式,可以预先设置@article
(尽管您可以真正使用 来模拟一个),并且可以请求update
动作和断言实际上是渲染了edit
模板的例子全部发生在一个示例中.
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 the update
action and the assertion that it actually renders the edit
template all happen in the one example.
这篇关于我在使用Rspec测试控制器的更新操作时遇到问题,我在做什么错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!