如何为简单的 PUT 更新编写 RSpec 测试? [英] How to write an RSpec test for a simple PUT update?
问题描述
我试图巩固我对 rails 和 BDD 工作流程的理解,所以我想通过创建其中一个迷你博客来从小事做起,但是使用 rspec.现在我有一个 ArticlesController 和 Article 模型,以及相关的 rspec 文件.文章很简单,只有标题:字符串和内容:文本,并且文章控制器是RESTful的——虽然文章的MCV是我亲手写的,但基本上和我用脚手架创建的一样.
I'm trying to solidify my understanding of rails and the BDD workflow, so I wanted to start small by creating one of those mini-blogs, but with rspec. Right now I have an ArticlesController and Article model, and associated rspec files. Article is very simple, has just title:string and content:text, and the ArticlesController is RESTful - although I hand wrote the MCV for Article, it's basically the same as if I used a scaffold to create it.
然而,当谈到在 rspec 中为 PUT 更新编写测试时,我真的不知道我在做什么.我正在使用 Factory Girl 创建文章对象,到目前为止我的代码如下所示:
However I don't really know what I'm doing when it comes to writing a test in rspec for the PUT update. I'm using Factory Girl to create the article object, and so far my code looks like:
#factories.rb
FactoryGirl.define do
factory :article do
title "a title"
content "hello world"
end
#articles_controller_spec.rb
before(:each) do
@article = Factory(:article)
end
describe "PUT 'update/:id'" do
it "allows an article to be updated" do
@attr = { :title => "new title", :content => "new content" }
put :update, :id => @article.id, :article => @attr
response.should be_successful
end
end
但是我不断得到:
Failures:
1) ArticlesController PUT 'update/:id' allows an article to be updated
Failure/Error: response.should be_successful
expected successful? to return true, got false
我做错了什么?我是否使用了正确的工具?当我运行我的测试服务器时,New、Edit、Destroy 都按照我的预期工作,所以我猜这是我对 RSpec 理解的问题.如果我错了,请告诉我 - 谢谢!
What am I doing wrong? And am I using the right tools? When I run my test server, New, Edit, Destroy all work as I would expect them to, so I'm guessing this is a problem with my understanding of RSpec. Let me know if I'm wrong - thanks!
推荐答案
你忘记了 .reload
你的 @article
,然后在 update
您的响应最有可能执行重定向的操作,因此
You forgot to .reload
your @article
, and on update
action your response most likely perform redirect, so
RSpec 2:
describe "PUT update/:id" do
let(:attr) do
{ :title => 'new title', :content => 'new content' }
end
before(:each) do
put :update, :id => @article.id, :article => attr
@article.reload
end
it { response.should redirect_to(@article) }
it { @article.title.should eql attr[:title] }
it { @article.content.should eql attr[:content] }
end
Rspec 3:
describe "PUT update/:id" do
let(:attr) do
{ :title => 'new title', :content => 'new content' }
end
before(:each) do
put :update, :id => @article.id, :article => attr
@article.reload
end
it { expect(response).to redirect_to(@article) }
it { expect(@article.title).to eql attr[:title] }
it { expect(@article.content).to eql attr[:content] }
end
这篇关于如何为简单的 PUT 更新编写 RSpec 测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!