【问题标题】:Shoulda: How would I use an instance variable outside of a setup or should block?应该:我将如何在设置之外使用实例变量或应该阻止?
【发布时间】:2010-04-20 01:10:15
【问题描述】:
我正在尝试执行以下操作:
@special_attributes = Model.new.methods.select # a special subset
@special_attributes.each do |attribute|
context "A model with #{attribute}" do
setup do
@model = Model.new
end
should "respond to it by name" do
assert_respond_to @model, attribute
end
end
end
但是,@special_attributes 在运行单元测试时超出了范围,在第 2 行留下了一个 nil 对象。我不知道在哪里/如何定义它以将其纳入范围。有什么想法吗?
【问题讨论】:
标签:
ruby
unit-testing
shoulda
【解决方案1】:
知道了(我想)。 Shoulda 在 Shoulda::Context 的上下文中执行块。在上述情况下,@special_attributes 是我的测试类的实例变量,而不是 Shoulda::Context。要解决这个问题,而不是使用实例变量,只需在上下文块中使用局部变量。
所以,例如:
context "Model's" do
model = Model.new
special_attributes = model.methods.select # a special subset
special_attributes.each do |attribute|
context "attribute #{attribute}" do
setup do
@model = model
end
should "should have a special characteristic"
assert_respond_to @model, attribute
...
end
end
end
end