12

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

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而不是像我上面所做的那样继续,但我没有不知道如何制作,以及它是否是“正确”/“正确”的制作方式。

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

4

2 回答 2

17

我是这样做的:

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 最近写了一本书Everyday Rails Testing with RSpec在他的博客上有一篇文章。他是这样描述的:

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
于 2012-05-11T09:45:20.240 回答
13

怎么样:

it "creates article" do 
  article_params = FactoryGirl.attributes_for(:article)
  expect { post :create, :article => article_params }.to change(Article, :count).by(1) 
end
于 2012-05-11T09:36:13.793 回答