基于条件的Rspec测试

时间:2019-02-15 07:19:28

标签: ruby unit-testing rspec

我有一个布尔变量condition。我有一些rspec测试用例来检查输入字段的存在。

if(condition == true)
   execute the following test cases. 
   it "some test case"
   end
   it "some test case 2"
   end

if(condition == false)
   execute the following test cases. 
   it "some test case 3"
   end
   it "some test case 4"
   end

但是所有测试用例都已执行。我尝试使用context

context "When condition is true"
  let(:condition) { TRUE }
  it "some test case"
  end
  it "some test case 2"
  end
context "When condition is false"
  let(:condition) { FALSE}
  it "some test case 3"
  end
  it "some test case 4"
  end

请让我知道在语法或初始化局部变量condition上是否有任何更改。

1 个答案:

答案 0 :(得分:0)

您可以使用RSpec documentation中所述的if:关键字

RSpec.describe "conditional contexts" do
  condition = true
  context "when true", if: condition do
    it 'passes' do
      expect(true).to be_truthy
    end
  end

  condition = false
  context "when false", if: !condition do
    it 'passes' do
      expect(false).to be_falsey
    end
  end

  condition = "non-nil"
  context "will not be run", if: condition.nil? do
    it 'will not get run' do
      expect(nil).to be_nil
    end
  end
end