如何编写RSpec测试以进行简单的PUT更新? [英] How to write an RSpec test for a simple PUT update?
问题描述
我试图巩固我对Rails和BDD工作流程的理解,所以我想通过创建其中一个迷你博客(但使用rspec)来从小处入手.现在,我有一个ArticlesController和Article模型,以及相关的rspec文件. Article非常简单,只有title:string和content:text,ArticlesController是RESTful的-尽管我是为Article亲自编写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创建article对象,到目前为止,我的代码如下:
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
这篇关于如何编写RSpec测试以进行简单的PUT更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!