0

通常在我的控制器规格中,我会做这样的事情:

describe MyController do
  describe 'POST #create' do
    let!(:my_model) { initialize_something_here }

    before :each do
      post :create, my_model: my_model
    end

    it 'should be successful' do
      response.should be_successful
    end

    ... more tests ...
  end
end

我的问题是,当我执行使用块的断言时,expect例如检查数据库中的项目计数是否在 a 之后增加create,我必须post从块中删除调用before :each,如下所示并为每个it语句重复它:

describe MyController do
  describe 'POST #create' do
    let!(:my_model) { initialize_something_here }

      it 'should insert into database' do
        expect { post :create, my_model: my_model }.to change(MyModel, :count).by(1)
      end

      it 'should be successful' do
        post :create, my_model: my_model
        response.should be_successful
      end

      ... more tests ...
    end
  end

有没有一种 DRY-er 的方式来post拨打电话?

4

1 回答 1

2

我相信您可以在 let 中使用 lambda

  let(:post_create_model) { -> { post :create, my_model }}

  it 'should insert into database' do
     expect(post_create_model).to change(MyModel, :count).by(1)
  end

  it 'should be successful' do
    post_create_model.call
    response.should be_successful
  end
于 2013-01-18T23:47:03.873 回答