0

Typically in my controller specs I'll do something like this:

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

My question is, when I do assertions that use an expect block such as checking that the count of items in the database is incremented after a create, I have to remove the post call from the before :each block, like this and repeat it for each it statement:

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

Is there a DRY-er way to do the post call?

1 Answer 1

2

I believe you can use a lambda for that maybe in a let

  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
Sign up to request clarification or add additional context in comments.

2 Comments

I suppose that could work... I was hoping there was a more concise or built-in way to do something like that.
Nice tip! Though could it be that the expect should be like this: expect(post_create_model).to change... (note the brackets)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.