3

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

第一的。每个 *_spec.rb 文件,应该scenario只存在一次?或者在一个文件中有多个scenario's 可以吗?

例如,在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

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

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

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

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

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

4

2 回答 2

7

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

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

二)这可能可以通过使用Rspec Set Gem和 Database Cleaner Gem 来解决。另外: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“添加”应该可以工作! 完整的 capybara API很有用,但我花了一些时间去摸索。最重要的是动作和 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

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

于 2011-06-20T01:57:09.553 回答
0

我不知道 capybara,但可以在此处找到可用方法的完整列表:

http://rubydoc.info/github/jnicklas/capybara/master#

希望,这有帮助

于 2011-06-19T20:40:44.433 回答