在控制器测试中干燥

时间:2013-06-24 17:26:12

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

我有很多这样的代码:

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 个答案:

答案 0 :(得分: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    
相关问题