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

Bac*_*cko 10 ruby controller rspec ruby-on-rails ruby-on-rails-3

我使用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
Run Code Online (Sandbox Code Playgroud)

也许,(注意:上面的代码与我用来测试new控制器动作的代码几乎相同)测试控制器动作的一种更好的方法create是在post :create动作过程中传递一些属性值,而不是像我上面那样继续,但我不喜欢不知道如何制作它,如果它是"正确"/"正确"的制作方式.

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

ck3*_*k3g 15

我是这样做的:

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

最近用RSpec撰写" Everyday Rails Testing "一书的Aaron Sumner 在他的博客上发表一篇文章.在哪里他这样描述:

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
Run Code Online (Sandbox Code Playgroud)


Vik*_*rón 13

怎么样:

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