Rspec 3 how to test flash messages

I want to test controller's action and flash messages presence with rspec.

action:

def create
  user = Users::User.find_by_email(params[:email])
  if user
    user.send_reset_password_instructions
    flash[:success] = "Reset password instructions have been sent to #{user.email}."
  else
    flash[:alert] = "Can't find user with this email: #{params[:email]}"
  end

  redirect_to root_path
end

spec:

describe "#create" do
  it "sends reset password instructions if user exists" do
    post :create, email: "[email protected]"      
    expect(response).to redirect_to(root_path)
    expect(flash[:success]).to be_present
  end
...

But I've got an error:

Failure/Error: expect(flash[:success]).to be_present
   expected `nil.present?` to return true, got false

You are testing for the presence of flash[:success], but in your controller you are using flash[:notice]


The best way to test flash messages is provided by the shoulda gem.

Here are three examples:

expect(controller).to set_flash
expect(controller).to set_flash[:success]
expect(controller).to set_flash[:alert].to(/are not valid/).now

If you are more interested in the content of the flash messages you can use this:

expect(flash[:success]).to match(/Reset password instructions have been sent to .*/)

or

expect(flash[:alert]).to match(/Can't find user with this email: .*/)

I would advise against checking for a specific message unless that message is critical and/or it does not change often.