在 rspec 的上下文中循环没有正确设置 let 变量

looping over inside a context in rspec doesn't set the let variable correctly

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 }

要解决此问题,您可以为每次迭代引入一个新的 context/describe 块:

  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