在rspec中的上下文内部循环无法正确设置let变量

问题描述 投票:0回答:1
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。我想一个个地遍历每个属性。

任何人都可以帮助我了解这里出了什么问题吗?

谢谢,

ruby-on-rails ruby rspec tdd rspec-rails
1个回答
1
投票

这是因为您正在重新定义每个循环的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
© www.soinside.com 2019 - 2024. All rights reserved.