测试“创建”控制器操作的正确方法是什么?

时间:2012-05-11 09:22:25

标签: ruby-on-rails ruby ruby-on-rails-3 rspec controller

我正在使用Ruby on Rails 3.2.2,Rspec 2.9.0和RspecRails 2.9.0。我想测试create控制器动作,但我不知道如何使它成为“正确”/“正确”的方式。我“搭建”模型,控制器,视图,...文件,所以在那些文件中我有Ruby on Rails生成器生成的公共代码;在我的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

也许,( note :上面的代码几乎与我用来测试new控制器操作的代码相同)更好的方法来测试create控制器操作将在post :create操作期间传递一些属性值,而不是像我上面那样继续,但我不知道如何制作它,如果它是“正确的”/“正确的“做事的方式。

那么,测试'创建'控制器操作的正确方法是什么?

2 个答案:

答案 0 :(得分:13)

怎么样:

it "creates article" do 
  article_params = FactoryGirl.attributes_for(:article)
  expect { post :create, :article => article_params }.to change(Article, :count).by(1) 
end

答案 1 :(得分:13)

我这样做:

describe "#create" do
  before { post :create, { "my_model"=> { "name"=>"name" } } }
  specify("should created one my_model") { change{ MyModel.count }.from(0).to(1) }
end

最近撰写该书Everyday Rails Testing with RSpec的Aaron Sumner有article at his blog。他在这里描述的是:

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