[英]What is the proper way to test 'create' controller actions?
I am using Ruby on Rails 3.2.2, Rspec 2.9.0 and RspecRails 2.9.0. 我使用Ruby on Rails 3.2.2,Rspec 2.9.0和RspecRails 2.9.0。 I would like to test the
create
controller action but I don't know how to make that the "right"/"proper" way. 我想测试
create
控制器操作,但我不知道如何使“正确”/“正确”的方式。 I "scaffolded" model, controller, view, ... files, so in those files I have the common code generated by Ruby on Rails generators; 我“搭建”模型,控制器,视图,...文件,所以在那些文件中我有Ruby on Rails生成器生成的公共代码; in my spec file I have:
在我的spec文件中我有:
it "assigns @article" do
new_article = FactoryGirl.build(:article)
Article.should_receive(:new).and_return(new_article)
post :create
assigns[:article].should eq(new_article)
end
Maybe, ( note : the above code is almost the same as that I use to test the new
controller action) a better way to test create
controller actions would be to pass some attribute value during the post :create
action instead of proceed as I make above , but I don't know how to make that and if it is the "right"/"proper" way to make things. 也许,( 注意 :上面的代码几乎与我用来测试
new
控制器动作的代码相同) 测试create
控制器动作的更好方法是在post :create
期间传递一些属性值post :create
动作而不是按照我的方式继续以上 ,但我不知道如何制作它,如果它是“正确”/“适当”的方式来制作东西。
So, what is the proper way to test 'create' controller actions? 那么, 测试'创建'控制器动作的正确方法是什么?
I'm doing it this way: 我是这样做的:
describe "#create" do
before { post :create, { "my_model"=> { "name"=>"name" } } }
specify("should created one my_model") { change{ MyModel.count }.from(0).to(1) }
end
Aaron Sumner who recently wrote the book Everyday Rails Testing with RSpec have an article at his blog . 最近用RSpec撰写“ Everyday Rails Testing ”一书的Aaron Sumner 在他的博客上发表了一篇文章 。 Where he describes it like this:
在哪里他这样描述:
describe "POST create" do
context "with valid attributes" do
it "creates a new contact" do
expect{
post :create, contact: Factory.attributes_for(:contact)
}.to change(Contact,:count).by(1)
end
it "redirects to the new contact" do
post :create, contact: Factory.attributes_for(:contact)
response.should redirect_to Contact.last
end
end
context "with invalid attributes" do
it "does not save the new contact" do
expect{
post :create, contact: Factory.attributes_for(:invalid_contact)
}.to_not change(Contact,:count)
end
it "re-renders the new method" do
post :create, contact: Factory.attributes_for(:invalid_contact)
response.should render_template :new
end
end
end
How about: 怎么样:
it "creates article" do
article_params = FactoryGirl.attributes_for(:article)
expect { post :create, :article => article_params }.to change(Article, :count).by(1)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.