ruby - 基于条件的 Rspec 测试

标签 ruby unit-testing rspec

我有一个 bool 变量 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 进行任何更改。

最佳答案

您可以使用 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

关于ruby - 基于条件的 Rspec 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54704368/

相关文章:

ruby-on-rails - 如何将分钟添加到 Time 对象

ruby-on-rails - Rspec - 结合 Expect_any_instance_of 和接收计数

ruby - Sinatra rspec capybara : "rack test requires a rack application"

ruby-on-rails - 如何设置 RSpec 进行性能测试 'on the side'

windows - IO.popen(my_cmd) - 子进程何时完成?

Ruby Prawn 将元数据添加到模板

java - 将模拟对象作为 JUnit 参数传递给带参数的测试方法

python - 模拟一个类实例的函数调用,该类实例是Python中另一个类实例的成员

ruby-on-rails - 将数组的数组拆分,[0] 拆分为一个,[1] 拆分为另一个

javascript - 为什么 ngForm "controls"属性在我的测试中为空? ( Angular )