ruby 在RSpec中使用哈希来检查不同的变量/值组合

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 在RSpec中使用哈希来检查不同的变量/值组合相关的知识,希望对你有一定的参考价值。

# Using hashes in RSpec to check different variable/value combinations
# Often in RSpec, you want to check all different combinations of values for a number of variables, such as in the following example:

RSpec.describe RealStateWorker do
  context "when active is true and rented is true" do
    it { expect(something).to eq(something) }
  end

  context "when active is true and rented is false" do
    it { expect(something).to eq(something) }
  end

  context "when active is false and rented is true" do
    it { expect(something).to eq(something) }
  end

  context "when active is false and rented is false" do
    it { expect(something).to eq(something) }
  end
end


# Because each variable has two possible values, there are four combinations to test. But, what if we had more variables? This can very quickly grow out of hand. Using hashes is a concise way of managing this:

RSpec.describe RealStateWorker do
  scenarios = [
    { active: true,   rented: true,  expected_result: :something      },
    { active: true,   rented: true,  expected_result: :something_else },
    { active: true,   rented: false, expected_result: :something      },
    { active: true,   rented: false, expected_result: :something_else },
    { active: false,  rented: true,  expected_result: :something      },
    { active: false,  rented: true,  expected_result: :something_else },
    { active: false,  rented: false, expected_result: :something      },
    { active: false,  rented: false, expected_result: :something_else }
  ]

  scenarios.each do |scenario|
    context "when active is #{scenario[:active]} and rented is #{scenario[:rented]}" do
      it "is #{expected_result}" do
        expect(something).to eq(scenarios[:expected_result])
      end
    end
  end
end

以上是关于ruby 在RSpec中使用哈希来检查不同的变量/值组合的主要内容,如果未能解决你的问题,请参考以下文章

由于符号而不是 Rails 导致哈希失败的 RSpec 测试

在编写rspec测试用例时如何覆盖ruby方法的局部变量?

Ruby Rspec:在不向源添加访问器的情况下测试实例变量

如何使用 pry 调试器检查 rspec 变量

何时使用 RSpec let()?

如何使用pry调试器检查rspec变量