2013-06-24 124 views
0

我有很多這樣的代碼:DRY在控制器測試

context 'with invalid attributes' do 
    it "does not save link to database" do 
    post :create, board_id: @board, link: FactoryGirl.attributes_for(:link, url: "") 
    expect(@board.links.count).to eq 0 
    end 

    it 're-render :new template' do 
    post :create, board_id: @board, link: FactoryGirl.attributes_for(:link, url: "") 
    expect(response).to render_template :new 
    end 

    it 'sets an error flash message' do 
    post :create, board_id: @board, link: FactoryGirl.attributes_for(:link, url: "") 
    expect(flash[:error]).to_not be_nil 
    end 
end 

如何我幹呢?所以我不會在每種情況下都有post :create, board_id: @board, link: FactoryGirl.attributes_for(:link, url: "")行?

回答

1

你可以嘗試before(:each)

context 'with invalid attributes' do 
    before(:each) do 
    post :create, board_id: @board, link: FactoryGirl.attributes_for(:link, url: "") 
    end 

    it "does not save link to database" do 
    expect(@board.links.count).to eq 0 
    end 

    it 're-render :new template' do 
    expect(response).to render_template :new 
    end 

    it 'sets an error flash message' do 
    expect(flash[:error]).to_not be_nil 
    end 
end  
+0

我做錯了什麼,因爲我有它這樣早,沒有工作,這一次它工作正常。這是一種神奇:),謝謝。 –