我是Ruby和Cucumber的新手,正在 The Cucumber Book 中进行一些练习。我正在尝试实现一项功能,因此用户可能不会退出atm。我在第3步定义中收到此错误:expected: 0 got: 20 (using ==) (RSpec::Expectations::ExpectationNotMetError)
。这是我的代码:
特点:
Feature: Prevent users from going overdrawn
Scenario: User tries to withdraw more than their balance
Given I have credited $100 in my account
When I withdraw $200
Then $0 should be dispensed
And I should be told that I have insufficient funds in my account
步骤定义:
Given /^I have credited (#{CAPTURE_CASH_AMOUNT}) in my account$/ do |amount|
my_account.credit(amount)
end
When /^I withdraw (#{CAPTURE_CASH_AMOUNT})$/ do |amount|
teller.withdraw_from(my_account, amount)
end
Then /^(#{CAPTURE_CASH_AMOUNT}) should be dispensed$/ do |amount|
cash_slot.contents.should == amount
end
Then /^the balance of my account should be (#{CAPTURE_CASH_AMOUNT})$/ do |amount|
my_account.balance.should eq(amount),
"Expected Then balance to be #{amount} but it was #{my_account.balance}"
end
支持模块:
module KnowsTheUserInterface
class UserInterface
include Capybara::DSL
def withdraw_from(account, amount)
Sinatra::Application.account = account
visit '/'
choose('amount-20')
click_button('Withdraw')
end
end
def my_account
@my_account ||= Account.new
end
def cash_slot
Sinatra::Application.cash_slot
end
def teller
@teller ||= UserInterface.new
end
end
World(KnowsTheUserInterface)
我的lib文件夹中的ruby文件:
class Account
def balance
@balance
end
def credit(amount)
@balance = amount
end
def debit(amount)
@balance -= amount
end
end
class CashSlot
def contents
@contents or raise("I'm empty!")
end
def dispense(amount)
@contents = amount
end
end
class Teller
def initialize(cash_slot)
@cash_slot = cash_slot
end
def withdraw_from(account, amount)
account.debit(amount)
@cash_slot.dispense(amount)
end
end
require 'sinatra'
get '/' do
%{
<html>
<body>
<form action="/withdraw" method="post">
<label for="amount">Choose amount here:</label>
<input type="radio" value="20" name="amount" id="amount-20">$20</input>
<input type="radio" value="40" name="amount" id="amount-40">$40</input>
<input type="radio" value="60" name="amount" id="amount-60">$60</input>
<input type="radio" value="100" name="amount" id="amount-100">$100</input>
<input type="submit" value="Withdraw"></input >
</form>
</body>
</html>
}
end
set :cash_slot, CashSlot.new
set :account do
fail 'account has not been set'
end
post '/withdraw' do
teller = Teller.new(settings.cash_slot)
teller.withdraw_from(settings.account, params[:amount].to_i)
end
我知道我对步骤定义如何相互通信有一些脱节。我在网上找不到任何参考资料。