Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec tests based on condition

I have a Boolean variable condition. I have some rspec test cases to check for the presence of an input field.

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

But all test cases are executed. I tried using 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

Please let me know if there any changes to be done either on the syntax or initializing the local variable condition.

like image 291
Chintu Karthi Avatar asked Feb 15 '19 07:02

Chintu Karthi


1 Answers

You can use the if: keyword as documented in RSpec documentation

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
like image 74
Kimmo Lehto Avatar answered Oct 14 '22 16:10

Kimmo Lehto