什么是测试“创建”控制器操作的正确方法? [英] What is the proper way to test 'create' controller actions?
问题描述
我使用Ruby on Rails 3.2.2,Rspec 2.9.0和RspecRails 2.9.0。我想测试创建
控制器操作,但我不知道如何使正确/正确的方式。我脚手架模型,控制器,视图,...文件,所以在那些文件我有Ruby on Rails生成器生成的公共代码;在我的spec文件中我有:
I am using Ruby on Rails 3.2.2, Rspec 2.9.0 and 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. I "scaffolded" model, controller, view, ... files, so in those files I have the common code generated by Ruby on Rails generators; in my spec file I have:
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
也许,(注意:上面的代码几乎和我用来测试 new
controller action)一个更好的测试 create
控制器动作的方法是在 post:create
动作,而不是像上面那样进行操作,但我不知道如何做,如果是right/
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.
因此,测试创建控制器操作的正确方法是什么?
推荐答案
如何:
it "creates article" do
article_params = FactoryGirl.attributes_for(:article)
expect { post :create, :article => article_params }.to change(Article, :count).by(1)
end
这篇关于什么是测试“创建”控制器操作的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!