2012-05-11 80 views
9

我使用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行動期間傳遞一些屬性值,而不是像我在以上那樣繼續進行,但我不知道如何做到這一點,並且如果它是「正確」/「正確」的製作方式。

因此,什麼是測試'創建'控制器操作的正確方法?

回答

13

如何:

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

也許你會說'... {職位:創建:文章=> article_params}。要......',而不是'... {職位:創建,article_params '.to ...'。 – Backo

+0

肯定的事,固定的,ta;) –

11

我做這樣說:

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 RSpecarticle 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 
相關問題