DRY rspec用于控制器规格的语法



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

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块进行断言时,例如检查数据库中的项目计数在create之后增加,我必须从before :each块中删除post调用,像这样并为每个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调用?

我相信你可以在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

相关内容

  • 没有找到相关文章

最新更新