gpt4 book ai didi

ruby-on-rails - 在使用 Capybara 的测试之间将用户保留在数据库中?

转载 作者:行者123 更新时间:2023-12-04 18:23:54 27 4
gpt4 key购买 nike

我的问题是我必须为每个单独的 capybara 测试创建一个新用户并登录。

一个例子如下:

require 'spec_helper'

describe "users" do
describe "user registration" do
it "should create a new user and log in" do
# Register a new user to be used during the testing process
visit signup_path
fill_in 'Email', with: 'testuser'
fill_in 'Password', with: 'testpass'
fill_in 'Password confirmation', with: 'testpass'
click_button 'Create User'
current_path.should == root_path
page.should have_content 'Thank you for signing up!'
end
end

describe "user login" do
it "should log in" do

# log in
visit login_path
fill_in 'Email', with: 'testuser'
fill_in 'Password', with: 'testpass'
click_button 'Log In'
current_path.should == root_path
page.should have_content 'Logged in!'
end
end
end

登录测试失败,因为该用户不再存在于该测试的数据库中。

这可以通过将两者放在一个测试中来解决,但我认为这是不好的做法。

此外,我还有另一个文件,目前正在使用 before_do 在每次测试之间注册和登录,这似乎也很糟糕...你 can see that code here .

作为记录,这是我的第一个 Rails 应用程序,所以也许我试图以错误的方式执行此操作。我想尽可能地把它弄干..

在需要用户登录的页面上使用 capybara 真的那么糟糕吗?

最佳答案

我已经这样做了。

require "spec_helper"

describe "Users" do
subject { page }
describe "User Registration" do
before { visit signup_path }

let(:submit) { "Sign up" }

describe "with invalid information" do
it "should not create a user" do
expect { click_button submit }.not_to change(User, :count)
end
end

describe "with valid information" do
before do
fill_in "Email", with: "user@example.com"
fill_in "Password", with: "foobar12"
fill_in "Password confirmation", with: "foobar12"
end

it "should create a user" do
expect { click_button submit }.to change(User, :count).by(1)
end

describe "after registration" do
before { click_button submit }
it { should have_content 'Thank you for signing up!' }
end

describe "after registration signout and login" do
let(:user) { User.find_by_email('user@example.com') }
before do
click_button submit
visit signout_path
sign_in user # sign_in is a method which u can define in your spec/support/utilities.rb . Define once and use at multiple places.
end
it { should have_content 'Logged In!' }
it { should have_link('Logout') }
end
end
end
end

#spec/support/utilities.rb
def sign_in(user)
visit sign_path
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Log in"
end

您的每一个 describeit块将在 before 之后运行这就是为什么我们需要在上述测试用例中的每个块中单击 click_button 的原因。

关于ruby-on-rails - 在使用 Capybara 的测试之间将用户保留在数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21706101/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com