Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 364
Mike Andrianov Avatar asked Jul 23 '14 20:07

Mike Andrianov


People also ask

How do I run a test in RSpec?

To run a single Rspec test file, you can do: rspec spec/models/your_spec. rb to run the tests in the your_spec. rb file.

How do flash messages work rails?

They are stored in the sessions cookie on the user's browser in order to persist for the next request. For the request following that one the flash hash clears itself out. They are not stored in the session cookie. They are merely associated with the session cookie.

What are RSpec tests?

RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.

What is RSpec DSL?

RSpec is a computer domain-specific language (DSL) (particular application domain) testing tool written in the programming language Ruby to test Ruby code. It is a behavior-driven development (BDD) framework which is extensively used in production applications.


2 Answers

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

like image 55
rabusmar Avatar answered Sep 20 '22 08:09

rabusmar


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 
like image 30
Robin Daugherty Avatar answered Sep 22 '22 08:09

Robin Daugherty