7

我是黄瓜的新手,我发现以下代码片段来测试设计登录功能。但是,似乎又少了一步,我没有找到任何解决方案:

Given /^that a confirmed user exists$/ do
  pending # express the regexp above with the code you wish you had
end

这里是以下代码:

功能/身份验证/session.feature

Feature: Session handling
  In order to use the site
  As a registered user
  I need to be able to login and logout

Background: 
  Given that a confirmed user exists

Scenario Outline: Logging in
  Given I am on the login page
  When I fill in "user_email" with "<email>"
  And I fill in "user_password" with "<password>"
  And I press "Sign in"
  Then I should <action>
  Examples:
    |         email       |  password   |              action             |
    | minimal@example.com |  test1234   | see "Signed in successfully"    |
    | bad@example.com     |  password   | see "Invalid email or password" |

Scenario: Logging out
  Given I am logged in
  When I go to the sign out link
  Then I should see "Signed out successfully"

特征/step_definitions/authentication_steps.rb

# Session
Given /^I am logged in$/ do
  visit path_to('the login page')
  fill_in('user_email', :with => @user.email)
  fill_in('user_password', :with => @user.password)
  click_button('Sign in')
  if defined?(Spec::Rails::Matchers)
    page.should have_content('Signed in successfully')
  else
    assert page.has_content?('Signed in successfully')
  end
end

规格/工厂/user.rb

Factory.define :minimal_user, :class => User do |u|
  u.username 'minimal'
  u.email 'minimal@example.com'
  u.password 'test1234'
  u.password_confirmation 'test1234'
end

这里是原始代码的链接

非常感谢您的帮助!!

4

3 回答 3

3

您的标题说“验证用户是否存在”,但这可能不是您需要在那里做的——您的Given步骤不需要断言某些东西有效,它们调用代码来为您的场景创建应用程序状态。当然,它们仍然是测试,因为它们仍然可能失败。

我想你正在寻找这样的东西:

Given /^that a confirmed user exists$/ do
  Factory.create(:minimal_user)
end

这将从您的工厂定义中创建并保存一个新的确认用户,以便场景的其余部分可以继续。

于 2010-11-02T23:38:02.080 回答
1

为了完成 Daniel 的回答,并且因为我启用了 Devise 可确认模块,我应该在我的夹具中添加一行以告知用户已确认。

例如:

Factory.define :minimal_user, :class => User do |u|
  u.username 'minimal'
  u.email 'minimal@example.com'
  u.password 'test1234'
  u.password_confirmation 'test1234'
  u.confirmed_at 'here the date you want'
end

此外,您可以在此处找到的调试步骤非常有用。

希望它可以帮助一些人。

于 2010-11-03T14:19:39.747 回答
0
(::) failed steps (::)

expected #has_content?("Signed in successfully") to return true, got false (RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/web_steps.rb:110:in `block (2 levels) in <top (required)>'
./features/step_definitions/web_steps.rb:14:in `with_scope'
./features/step_definitions/web_steps.rb:108:in `/^(?:|I )should see "([^"]*)"(?: within "([^"]*)")?$/'
features/authentication/session.feature:16:in `Then I should <action>'

undefined method `email' for nil:NilClass (NoMethodError)
./features/step_definitions/authentication_steps.rb:43:in `/^I am logged in$/'
features/authentication/session.feature:23:in `Given I am logged in'
于 2010-11-03T00:06:52.667 回答