测试“创建"控制器操作的正确方法是什么? [英] What is the proper way to test 'create' controller actions?

查看:19
本文介绍了测试“创建"控制器操作的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ruby on Rails 3.2.2、Rspec 2.9.0 和 RspecRails 2.9.0.我想测试 create 控制器操作,但我不知道如何使其成为正确"/正确"的方式.我搭建"了模型、控制器、视图、...文件,所以在这些文件中我有由 Ruby on Rails 生成器生成的通用代码;在我的规范文件中,我有:

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控制器动作的代码几乎一样)一种更好的测试create 控制器动作将是在 post :create 动作期间传递一些属性值,而不是像我上面所做的那样进行,但我不知道如何做到这一点以及它是否是正确"/正确"的制作方式.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆