Devise user creation fails during Capybara integration testing (and Selenium webdriver) - ruby-on-rails

I'm trying to create a user during an integration test to use for some operations. I'm using devise with :confirmable. The code is the following:
user = User.create({username: "user1", password: "pass1234", password_confirmation: "pass1234", email: "test#email.com"})
user.confirm!
fill_in "Username", :with => user.username
fill_in "Password", :with => user.password
click_button "Sign in"
The problem is that the login fails every time I try it. There are no errors about the user creation, but for some reason the user doesn't seem to "be there" when I try to login. I just get 'Invalid username or password' when I try to sign in. This seems like something to do with the fact that maybe Capybara/Selenium webdriver isn't waiting properly for the database operation to take place before it tries to sign in. If that's the case, how could I test it or fix it?
Is it "wrong" to even be trying to insert into the database during an integration test?

I don't use devise myself so can't really comment on the specifics of the problem you're encountering, but this question caught my eye:
Is it "wrong" to even be trying to insert into the database during an integration test?
Yes, I would say it generally is.
Your integration tests should test your code from the point of view of the user:
Expectations should only depend on what the user can actually see.
Actions should correspond only to what the user can actually do.
Inserting something into the database goes beyond the range of actions that the user has at their disposal. It is something for a unit test perhaps, but not for an integration test.
That being said, you could argue that seeding database data is a bit of an exception to this rule, since you're setting up context for your test (see my comments below).

Related

Cannot reach the password of the user after assigning it - RSpec

I am trying to write system tests. I want to run a classic login page test.
I have a field for email, password, and submit button.
It is working in production env and alive without any problem.
my test file is like this:
it "can login" do
user = User.create(email: 'mail#mail.com', password: 'password', role:1, name: 'test user')
user.save!
visit '/'
fill_in(:user_email, with: user.email)
fill_in(:user_password, with: 'password')
find(:button, 'Sign in').click
expect(page).to have_content('Signed in.')
end
Whenever I tried to create a user and try to use it in the system testing, it is not working. It is visiting the page, filling the places and clicking the button as it should but it cannot log in, giving error that email or password is not correct.
I believe there is a problem with password encryption or somehow I cannot match the passwords properly.
I have printed out the user after creation in the test case, I have a valid user but somehow I cannot reach its password. I checked the model, there is not a 'password' field. ( I am working on a company project, that is why I am having difficulty to find the problem )
I can assign a password with using user.password = ... but I cannot call it back it seems. (I tried this in rails console, assigning worked, calling back did not and I could use the user and the password for logging in manually)
EDIT:
I found out that the problem is database matching. I could create the user but the test is not using that user...
I found the problem. It was because of data transaction. I changed it truncation for system testing and it worked! It was basically flushing all the data before using it. That was why I was getting error.

Capybara test case for Login page authentication

I have capybara test case below.
it "Testing login page with valid data" do
fill_in 'email', with: 'kiran#gmail.com'
expect(page).to have_selector("input[value='kiran#gmail.com']")#Checking values are inserted in email field
fill_in 'password', with: 'Kiran.6565'
expect(page).to have_selector("input[value='Kiran.6565']")#Checking values are inserted in password field
click_button('submit')
expect(current_path).to eql(patient_detail_path(4))
end
I am checking Login page once the email and password fields are matches it should redirect to patient_details_path with id field value. In above code i specified email and password is working fine for manual login, but problem is in test case. Expected result: it should redirect to another page(patient_details_path) but it redirecting to home page(/) again.
Failures:
1) Login Page Interface Test login page with valid data
Failure/Error: expect(current_path).to eql(patient_detail_path(4))
expected: "/patient_details/4"
got: "/"
(compared using eql?)
# ./spec/views/login_spec.rb:41:in `block (2 levels) in <top (required)>'
Finished in 1.08 seconds (files took 2.13 seconds to load)
14 examples, 1 failure
I tried different solution's from stackoverflow but nothing work for me. Below are the different solution's tried.
#expect(current_path).to eql(patient_detail_path(4))
#expect(page).to have_current_path(patient_detail_path(4))
If email and password mismatch it will throw an error and redirect to login page again. In my scenario it was throwing an error even if email and password are valid . If i add below code in my test case it will work pass the test case.
#expect(page).to have_content "Invalid username/password combination"
Any one please help me i am new to ruby on rails and capybara.
I'm guessing the test you're trying to write should be written something like
before :each do
#user = # Create the required user with whatever method you're using
#patient = # Create the required patient with whatever method you're using
end
it "Logs in with valid data" do
visit(patient_detail_path(#patient)) # gets redirected to the login path
fill_in 'email', with: 'kiran#gmail.com'
fill_in 'password', with: 'Kiran.6565'
click_button('submit')
expect(page).to have_current_path(patient_detail_path(#patient))
end
That's a general guess and might not be 100% correct (tough to guess exactly what you're trying to do with half the test missing - the before block - from your question) but the general parts should be there. Since yours isn't logging in I'm guessing you're not actually creating a valid user with the given email and password, or you don't have a patient created with an id of 4 (you really shouldn't be relying on testing specific id numbers in feature tests though).
Additionally, you should always use the have_current_path matcher when checking for a given path/url since it will prevent test flakiness and since it's not a view test it shouldn't be in spec/views/login_spec.rb, more appropriate would be spec/features/login_spec.rb.
It seems to me that the driver is capturing the URL before Rails has a chance to update the URL to reflect the new page.
Asserting on URL is hard after performing a navigation change as a race condition might appear. I would suggest:
Assert on some other piece of info that could verify the user successfully logged in.
Assert using the wait option.
expect(page).to have_current_path(patient_detail_path(#patient), wait: 3)

How to access the same DB data that Capybara uses

I have a very simple password reset form, which is just a text field to enter an email and a submit button.
There are some client-side validations using JS, so I use the Capyabara JS driver when writing spec tests for it.
This test just tests that a password reset token is added to the user's auth_info table.
describe "password reset form", js: true do
let(:email) { "foo#example.com" }
# Create existing user with an email so we can reset it's password
let!(:user) { create(:user, email: email) }
before(:each) do
fill_in email_field, with: email
click_button reset_button
end
it "generates a new token" do
# `token` is definitely getting set properly when I pause it here
# with binding.pry and inspect the object using `user.reload`
# But when running the test it always shows up as `nil`
expect(user.reload.auth_info.token).to match(/[A-Fa-f0-9]{32}/)
end
end
As the comment notes, I know for a fact the token is getting properly set when I inspect it directly using binding.pry. But RSpec and Capybara are seeing it as nil, even after refreshing the model using reload.
Is Capybara maintaining a different cache or something?
Thanks!
EDIT: Also tried different combinations of applying the reload to the User model as well as the AuthInfo model, in case I needed to refresh the latter too
You're using a JS capable browser which means click_button is asynchronous. The result of this is you're executing click_button and then immediately checking for the token before the action triggered by the button has occurred. You can verify this by putting sleep 5 before the expect and the test should pass. The correct way to make the test wait before the check is to use capybaras matchers to look for info on the page that changes once the click_button has completed, something like either of the following
expect(page).to have_text('text that appears after click_button has succeeded')
expect(page).to have_selector('div.abcde') #element that appears after click_button has succeeded
Those will make the test wait until the action has completed and then you can check for the token

How to avoid hard coding values in cucumber features?

When writing my scenerios, is it possible to not have to hard code text in the steps?
Like say I am insert a username in a textbox field, and a password in the password field.
If I need to do this in many places, it would be a pain to fix.
Example:
Given I am the registered member "myusername"
And I am on the login page
When I fill in "email" with "email#example.com"
And I fill in "password" with "123"
And I press "Login"
Then I should see "Account Activity"
I don't want my username, email, and password hard-coded.
Okay, you're still using the older version of the cucumber-rails gem which comes with the training wheels installed by default. Read this post by Aslak Hellesøy "The training wheels came off".
The gist of the post is that using web_steps.rb, although it having been the "standard" for years is now terribly wrong and that we should feel bad for doing that.
The purpose of Cucumber is to use it to make readable / understandable features for all people.
Writing a scenario like this is long and boring:
And I am on the login page
When I fill in "email" with "email#example.com"
And I fill in "password" with "123"
And I press "Login"
Then I should see "Account Activity"
What you want to actually be testing is that you should be able to login and after that see something to do with being logged in. Whatever that something is shouldn't be written in the scenario.
So ideally, your Scenario (in a more exciting fashion) would look like this:
When I login successfully
Then I should see that I am logged in
Then the task of doing the legwork goes to some new step definitions. Those two steps aren't defined automatically for you, like web_steps.rb does, but rather need to have them written in a file within feature/step_definitions. What you call the file is up to you, but it'll contain content similar to this:
When /I login successfully/ do
visit root_path
click_link "Login"
fill_in "Email", :with => "you#example.com"
fill_in "Password", :with => "password"
end
Then /^I should see I am logged in$/ do
page.should have_content("Account Activity")
end
No more excessive web_steps.rb file and cleaner step definitions. Exactly what Cucumber should be.
Create a step to encapsulate the logging in behavior as described here
If this works for you, I would then suggest tweaking the Given /I am logged in/ step to capybara calls to get a slight boost to performance. Also, in the future it is recommended that you avoid using web_steps for reasons described here.
Ryan's example is a change from imperative steps to declarative. This is generally a better idea. It means that the implementation has been moved into step definitions which makes the feature more readable and focuses on the behavior instead of the details.
But if you need to be specific with your steps (imperative), you could try something like
Given I am a registered member
And I am on the login page
When I fill in the login form
And I submit the login form
Then I should see I am logged in
You could also combine those steps to make it even simpler. But still, Ryan's idea is probably better in most cases.
Edit: Ryan has written a book. It's quite good. Hi Ryan!
You can create csv file in framework under data folder,add your private values to csv file, then call it in your feature file

Cucumber and Clearance: current_user in steps

What I what to accomplish is to use (rely on) current_user method while defining Cucumber steps. I'm using Clearance in my project.
First of all I tried to use sign_in but it didn't work (I guess Cucumber World doesn't know about Clearance methods...).
So how do I make Cuckes recognize current_user and sign_in/sign_out methods?
Your Cucumber features should be driving your application through the public user interface. Something like:
Given /^I am signed in as "([^\"]*)"%/ do |username|
visit 'sign_in'
fill_in 'Username', :with => username
click 'Sign In'
end
Since the current_user method isn't available to the browser, you shouldn't be using it in your spec.
You could fake it in your steps by storing #current_user in the above step and then providing an attribute reader for it.
I disagree with the idea that every acceptance test (cucumber or otherwise) must exercise the login logic. Luckily, if you agree, Clearance has added a back door in tests that lets you skip the sign in steps.
user = create(:user)
visit posts_path(as: user)
Now you can leave your login-related features driving the login ui as a user would and skip that for features that aren't directly related to logging in.

Resources