【问题标题】:What is the proper way to test 'create' controller actions?测试“创建”控制器操作的正确方法是什么?
【发布时间】:2012-05-11 09:22:24
【问题描述】:

我正在使用 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 操作期间传递一些属性值,而不是像我上面所做的那样继续,但我不知道如何做到这一点,以及它是否是“正确”/“正确”的制作方式。

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

【问题讨论】:

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


    【解决方案1】:

    我是这样做的:

    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
    

    【讨论】:

      【解决方案2】:

      怎么样:

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

      【讨论】:

      • 也许你会说... { post :create, :article => article_params }.to ...而不是... { post :create, article_params }.to ...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      相关资源
      最近更新 更多