基于条件的 Rspec 测试

8

我有一个布尔变量 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


请问您能否添加您想要运行测试的代码? - Tanay Sharma
嗨,我改变了问题的格式,以显示代码。上下文是我想要运行的代码。在我的情况下,两个上下文中的所有测试用例都被执行了,我只想根据变量“condition”的布尔值一次执行一个上下文。 - Chintu Karthi
1
if应该已经起作用了。 - Sergio Tulentsev
“condition” 是从哪里来的?它在哪里定义?它是你的测试套件的一部分吗?还是一个全局变量?或者是你正在测试的代码中的条件? - spickermann
我在测试文件index.html.haml_spec.rb中使用let声明了一个变量,如下:let(:condition_variable) { TRUE }。这是我用作变量的内容。 - Chintu Karthi
显示剩余2条评论
1个回答

11
你可以使用 if: 关键字,如 RSpec 文档 所述。
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

1
哦,不错,我不知道这个。 - Sergio Tulentsev
嗨。谢谢你的回答,我尝试了你的例子,但没有使用非nil部分(只有true和false)。问题是两个上下文中的测试用例都在执行。我不确定为什么会这样。这是我在Rspec.describe函数中创建变量的方式。let(:condition) { true }。请告诉我我哪里做错了。谢谢。 - Chintu Karthi
嗨。现在它正在工作。我只需要知道,为什么我们在每个上下文中都要指定条件值为true和false?我们不能只分配一次为true或false,然后像if{}else{}条件一样检查吗? - Chintu Karthi
@ChintuKarthi 晚回答 :) 你可能可以。它只需要在 if: 后面加上一些布尔值,甚至可以是像 if: ENV["foo"] == "bar" 这样的东西。 - Kimmo Lehto
1
有人有最新的文档链接吗? 这个答案中的链接似乎不再有效。 - jayhendren

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接