gpt4 book ai didi

ruby-on-rails-3 - 关于 capybara 的几个问题

转载 作者:行者123 更新时间:2023-11-28 19:55:56 25 4
gpt4 key购买 nike

我有几个关于 capybara 的问题。我不妨在这里问一下,因为 github page for Capybara 中的 RDOC非常适合设置和运行它。但是 API 或可用方法列表在哪里?

首先。每个 *_spec.rb 文件,scenario 应该只存在一次吗?或者在一个文件中包含多个场景是否合适?

例如,在spec/request/user_spec.rb中:

require 'spec_helper'

feature 'User actions' do
background do
data = {
:first_name => 'foo',
:last_name => 'bar',
...
}

user = User.new(data, :as => :user)
user.save
end

scenario 'User can browse home page' do
visit root_path
page.should have_content('Homepage')
end

scenario 'User should not be able to visit the dashboard' do
visit dashboard_root_path
page.should have_content('You are not authorized to access this page.')
end
end

如果上面的代码结构有什么问题,或者是否有改进的余地。我是开放的反馈。

其次。我注意到上面的代码。如果我在 spec/spec_helper.rb 中有 config.use_transactional_fixtures = false,它会为用户节省两次。这意味着,在我的测试数据库/用户表中,我将有 2 个名为“foo bar”的用户。这正常吗?

第三。 我有一个带有 HTML 按钮的表单。当用户点击这个按钮时,jQuery 提交表单。我将如何用 Capybara 测试它?我不认为 click_button "Add" 会成功。

第四。我如何在 Capybara 中登录用户?我正在使用设计。 sign_in User.first 会成功吗?我可以在 Capybara 中访问 current_user 吗?

最后,如果有人知道任何关于 Rspec + Capybara 的“入门”指南/教程。请务必提及。

最佳答案

自从我决定不再喜欢 Cucumber 后,我也转而编写请求规范。

ONE) 有多个场景确实很好。您可以使用 rspec 的所有其他强大功能,因此我建议您也使用底部代码中的上下文。

二)这可能可以通过使用 Rspec Set Gem 来解决。和数据库清洁 gem 。还有:The Original Rationale for Set

警告:确保在使用 set 时正确设置 DatabaseCleaner。我自己的设置(可能有点矫枉过正,但对我有用):

config.before(:suite) do
DatabaseCleaner.clean_with :truncation
end

config.before(:all) do
DatabaseCleaner.clean_with :truncation
end

config.after(:all) do
DatabaseCleaner.clean_with :truncation
end

config.after(:suite) do
DatabaseCleaner.clean_with :truncation
end

三)是的! click_button“添加”应该可以工作! The complete capybara API很有用,但花了我一段时间才理解。最重要的是 Action 和 rspec 匹配器。

例子:

click_button "Add"
page.should have_content("Successfully Added")

您可以使用元素查找器缩小范围。

第四)设计提供帮助。有一个登录助手。阅读 dox :)。这是一个演示:

feature 'User actions' do
background do
data = {
:first_name => 'foo',
:last_name => 'bar',
...
}

@user = User.new(data, :as => :user)
@user.save
end

context "no user is signed in" do
scenario 'User can browse home page' do
visit root_path
page.should have_content('Homepage')
end

scenario 'User should not be able to visit the dashboard' do
visit dashboard_root_path
page.should have_content('You are not authorized to access this page.')
end
end

context "user is signed in" do

before :each do
sign_in @user
end

[more scenarios]
end
end

当然,最终您可能希望将其拆分为更具体的功能。可能有一个“公共(public)导航”功能用于所有关于客人看到内容的测试,然后一个单独的功能用于用户登录等。

关于ruby-on-rails-3 - 关于 capybara 的几个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6404632/

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