控制器规范的DRY rspec语法

时间:2013-01-18 23:12:26

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

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

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之后递增,我必须删除postbefore :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

是否有干扰方式进行post通话?

1 个答案:

答案 0 :(得分: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