I want to use Rspec expect method around

Asked 1 years ago, Updated 1 years ago, 283 views

I am writing a test code using Rspec, but I want to define it somewhere and define it for each it like a method.
I'm in trouble because I can't find the same article as I thought.
I wonder how dry they are in this situation at the development site.

The following expect .toeq1 appears many times, and the number of expect .toeq2 will increase further in the future, so I would like to reduce the burden and oversight when writing in one place.

Please let me know if you are familiar with it.Thank you.

it 'value returned with privilege A' do
  expect .to eq1
end

it's return value with privilege B'do
  expect .to eq1
end

'it' privilege C returns value' do
  expect .to eq1
end

ruby-on-rails ruby rspec

2022-12-19 02:01

2 Answers

If you use shared_examples, you can make it common, but I'm not sure if the amount of description will decrease.
I think it's often easier to handle the test if you don't use it as a DRY.

describe do
  shared_examples "value is 1" do
    it do
      expect(expected).toeq1
    end
  end

  context do
    let(:expected) {1}
    include_examples "value is 1"
  end

  context do
    let(:expected) {1}
    include_examples "value is 1"
  end
end


2022-12-19 03:57

I don't know if it meets the requirements, but I can write rspec-parameterizedgem as follows:

describe do
  where(:condition,:expected) do
    [
      ['a', 1]
      ['b', 2]
      ['c',3',
    ]
  end
  with_them do
    it do
      expect(hoge(condition))).to eq expected
    end
  end
end
# expect(hoge('a')).to eq1
# expect(hoge('b')).to eq2
# expect(hoge('c')).to eq3
# same as


2022-12-19 10:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.