在 Rspec 中的上下文中循环访问不会正确设置 let 变量


MY_HASH = {
user_id: [:email, :first_name],
email: [:last_name]
}
context "when object's single attribute changed" do
let(:object) { double("my_object", :changed? => true) }
before do
allow(object).to receive("#{attribute}_changed?").and_return(true)
end
after do
allow(object).to receive("#{attribute}_changed?").and_return(false)
end
MY_HASH.each do |attr, dependent_attrs|
let(:attribute) { attr }
it "should have all dependent attributes in right order for defaulting attribute" do
expect(subject.send(:my_method)).to eq(dependent_attrs)
end
end
end

此处属性始终计算为email。我想逐个迭代每个属性。

谁能帮我了解这里出了什么问题?

谢谢

这是因为您重新定义了每个循环attribute

MY_HASH.each do |attr, dependent_attrs|
let(:attribute) { attr }

要解决此问题,您可以为每次迭代引入一个新的上下文/描述块:

MY_HASH.each do |attr, dependent_attrs|
describe("#{attr}") do
let(:attribute) { attr }
it "should have all dependent attributes ..." do
# content of test here
end
end
end

最新更新