How to declare a variable shared between examples in RSpec?

后端 未结 3 1709
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 14:01

Suppose I have the following spec:

...
describe Thing do

  it \'can read data\' do
     @data = get_data_from_file  # [ \'42\', \'36\' ]
     expect(@data.count         


        
3条回答
  •  没有蜡笔的小新
    2021-02-01 14:17

    I just ran into this same problem. How I solved it was by using factory_girl gem.

    Here's the basics:

    create a factory (here's a code snippet:

    require 'factory_girl'
    require 'faker' # you can use faker, if you want to use the factory to generate fake data
    
    FactoryGirl.define do
      factory :generate_data, class: MyModule::MyClass do
        key 'value'
      end
    end
    

    Now after you made the factory you need to make a Model that looks like this:

    Module MyModule
      class MyClass
        attr_accessor :key
    
        #you can also place methods here to call from your spec test, if you wish
        # def self.test
            #some test
        # end
      end
    end
    

    Now going back to your example you can do something like this:

    describe Thing do
      before(:all) do
      @data = FactoryGirl.build(:generate_data)
      end
    
      it 'can read data' do
         @data.key = get_data_from_file  # [ '42', '36' ]
         expect(@data.key.count).to eq 2
      end
    
      it 'can process data' do
         expect(@data.key[0].to_i).to eq 42  # @data will not be nil. at this point. whatever @data.key is equal to last which was set in your previous context will be what data.key is here
      end
    
    end
    

    Anyways, good luck let us know, if you got some other solution!

提交回复
热议问题