因此,我有一个复杂的RPG角色模型,我正在作为一个附带项目工作。对于这个RPG,有6个基本的“能力分数”(力量,灵巧,体质,智力,智慧,魅力)。我特别关注将它们设置为0的测试,这应该是无效的(字符死亡等)。以下是我在rspec中的内容:
describe "when ability scores are 0" do
ability_scores = %w(strength dexterity constitution
intelligence wisdom charisma)
ability_scores.each do |ability_score|
@character.ability_score = 0
expect(@character).to be_invalid
end
end文件开头有一个工厂,创建了一个完全有效的字符并设置了subject { @character }
我认为它会看到ability_score,并考虑在计算字符对象之前插入它的值,但情况似乎并非如此。
将@character.send(:"#{ability_score}=", 0)切换到@character.ability_score = 0会导致NoMethodError: undefined method 'strength=' for nil:NilClass
但是,单独的describe块可以正常工作:
describe "when strength is 0" do
before { @character.strength = 0 }
it { should_not be_valid }
end但其中有6个是一堆杂乱的东西。
有什么想法吗?
发布于 2014-02-21 20:52:28
这一行有问题
character.ability_score = 0这一行在:ability_score=对象上发送一个名为character的方法,但我认为您想要的是设置正在迭代的字符串数组所引用的变量。
幸运的是,您可以使用send调用对象上的任意方法。可以将字符串转换为引用setter方法的符号,然后将其作为消息发送给character。
character.send(:"#{ability_score}=", 0)(注意:您实际上不需要发送一个符号;如果您愿意,可以将它作为字符串保存)。实际上,这与调用character.strength = 0等非常相似。
编辑
更改describe块的内容以定义测试:
describe "when ability scores are 0" do
%w(strength dexterity constitution intelligence wisdom charisma).each do |ability_score|
it "is invalid when #{ability_score} is 0" do
@character.send("#{ability_score}=", 0)
expect(@character).to be_invalid
end
end
endhttps://stackoverflow.com/questions/21944691
复制相似问题