所以我试图在 Ruby 中创建一个字典对象,并让它作为项目的一部分通过一堆 RSPEC 测试。到目前为止一切都很好,但我被困在一项特定的测试中。这是该测试之前的 RSPEC:
require 'dictionary'
describe Dictionary do
before do
@d = Dictionary.new
end
it 'is empty when created' do
@d.entries.should == {}
end
it 'can add whole entries with keyword and definition' do
@d.add('fish' => 'aquatic animal')
@d.entries.should == {'fish' => 'aquatic animal'}
@d.keywords.should == ['fish']
end
it 'add keywords (without definition)' do
@d.add('fish')
@d.entries.should == {'fish' => nil}
@d.keywords.should == ['fish']
end
it 'can check whether a given keyword exists' do
@d.include?('fish').should be_false
end
it "doesn't cheat when checking whether a given keyword exists" do
@d.include?('fish').should be_false # if the method is empty, this test passes with nil returned
@d.add('fish')
@d.include?('fish').should be_true # confirms that it actually checks
@d.include?('bird').should be_false # confirms not always returning true after add
end
end
到目前为止,除了最后一个测试“在检查给定关键字是否存在时不作弊”之外,一切都通过了。我正在努力思考如何才能让它通过,但到目前为止还没有成功。任何帮助将不胜感激。这是我到目前为止所拥有的:
class Dictionary
attr_accessor :keywords, :entries
def initialize
@entries = {}
end
def add(defs)
defs.each do |word, definition|
@entries[word] = definition
end
end
def keywords
input = []
@entries.each do |key, value|
input << key
end
input.sort
end
def include?(key)
self.keywords.include?(keywords.to_s)
end
end
提前致谢!