mercredi 12 octobre 2016

Ruby on Rails Controller Testing: Simulating Login for Controller Testing

I'm new to controller testing on rails. Currently I've been able to figure out the very basics for controller testing, such as running a :get request and asserting expect(response).to be_success or expect(response).to redirect_to login_url, as well as other basics, like asserting the appearance of HTML elements on the page.

But how would I go about testing a more complex program flow? For example, I would like to simulate a login, and attempt to authenticate a user with invalid parameters, such as invalid password or a blank e-mail/password, and assure that it loads the associated flash method written into my controller. Here's what my current test looks like:

describe SiteController, :type => :controller do 

    describe "guest access" do
        context "When a guest trys to access a page that requires authentication" do
            it "info page" do
                get :page
                expect(response).to redirect_to login_url
            end
        end
    end

    describe "logging in" do
        context "when a user tries to login without valid login details" do
            it "attempts to login with blank email and password" do
                #Create User with Blank Login Details
                user = User.create(:id => rand(100000), :first_name => "", :last_name => "", :email => "", :password => "")
                #How do I attempt to run the login post method with the above and run the post- submission of login form?
                post :login
                expect(response).to redirect_to login_url
                expect(flash[:notice]).to match(/^Your email and password did not match. Please try again./)
            end
        end
    end
 end

Note: I am not using devise, just the built in rails authentication.

Aucun commentaire:

Enregistrer un commentaire