I want to test my create user function in ruby on rails using capybara but I am always redirected to the login page. Is there a way that I can test the create function without logging in?
`require 'rails_helper'
RSpec.feature "Users", :type => :feature do before do begin # login_as(FactoryBot.create(:user)). @user = FactoryBot.create(:user) rescue StandardError => e puts "#{e.message}" end end
it "Creates a new User" do
begin
visit user_session_path
#visit "/"
fill_in :first_name, :with => "{@user.first_name}"
fill_in "middle_name", :with => "{@user.middle_name}"
fill_in "last_name", :with => "{@user.last_name}"
fill_in "username", :with => "{@user.username}"
click_button "Create User"
rescue StandardError => e
puts "#{e.message}"
end
end
end`
It's not fully clear whether you're talking about a user that has the rights to create other users, or you just have a user sign up page on your app. The first part of this answer is for the former.
You can't test the page in a feature test without logging in (unless the page doesn't require a user to be logged in) but using the Devise helpers you can skip the step of actually going to the login page and logging in. See https://github.com/heartcombo/devise/wiki/How-To:-Test-with-Capybara
Wherever you're configuring RSpec include the Warden helpers
RSpec.configure do |config|
config.include Warden::Test::Helpers
end
Then in your test use the login_as
helper to log in as a user that has rights to create a user
...
login_as(FactoryBot.create(:admin)) # assumes you have a factory named `admin` that will create a user with the permissions to create other users
visit 'whatever page allows creating a new user'
new_user = FactoryBot.build(:user) # don't create here because you don't want it saved
fill_in "first_name", with: new_user.first_name
fill_in "middle_name", with: new_user.middle_name
fill_in "last_name", with: new_user.last_name
fill_in "username", with: new_user.username
click_button "Create User"
expect(page).to have_text "Successfully created new user!"
...
For the second interpretation of you question, if you just have a signup page where people can create a user, then you either don't have the authentication requirements correctly set for the controller action or the fact that you're creating the user in the DB before filling in the info in the UI is creating a collision on a unique field. You can fix that by just building the FactoryBot user rather than creating
...
user = FactoryBot.build(:user) # will build a valid user but won't commit it to the DB
fill_in :first_name, with: user.first_name
fill_in "middle_name", with: user.middle_name
fill_in "last_name", with: user.last_name
fill_in "username", with: user.username
click_button "Create User"
# expectation on whatever should happen in the UI goes here