在水豚中进行测试前登录

问题描述 投票:0回答:1

我想使用capybara在ruby on rails上测试我的创建用户功能,但是我总是被重定向到登录页面。有没有一种方法可以在不登录的情况下测试create函数?

`需要'rails_helper'

RSpec.feature“用户”,:type =>:功能做之前开始#login_as(FactoryBot.create(:user))。@user = FactoryBot.create(:user)抢救StandardError => e放置“#{e.message}”结束结束

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

结束`

devise capybara rspec-rails
1个回答
0
投票

尚不清楚您是在谈论有权创建其他用户的用户,还是在应用上拥有用户注册页面。该答案的第一部分是针对前者的。

您无法在未登录的情况下在功能测试中测试该页面(除非该页面不需要用户登录),但是使用Devise帮助器,您可以跳过实际进入登录页面并登录的步骤。 in。请参见https://github.com/heartcombo/devise/wiki/How-To:-Test-with-Capybara

无论您在配置RSpec时,包括Warden帮助程序

RSpec.configure do |config|
  config.include Warden::Test::Helpers
end

然后在您的测试中使用login_as帮助程序以具有创建用户权限的用户身份登录

...
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!"
...

对于您的问题的第二种解释,如果您仅拥有一个可以由用户创建用户的注册页面,那么您可能没有为控制器操作正确设置身份验证要求,或者您是在创建用户在DB中填写UI信息之前,正在唯一字段上创建冲突。您可以通过构建FactoryBot用户而不是创建]来解决此问题。

...
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
© www.soinside.com 2019 - 2024. All rights reserved.