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

Everyday Rails Testing with RSpecという本を最近書いた 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
于 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 に答える