Rspec populating a variable with data from an external file

I am still the new rspec top, so please excuse me if this is simple, but I could not find the answer on Google. I have a library module that handles parsing some data from an API response. I wrote tests and it all works great, however I would like to move the fake API response data to an external file, as it is quite long and makes the test harder to read. I looked at fixtures and factories, but this is valid for models, and this is just a very long piece of xml. My current test looks something like this.

describe :my_test do let(:my_var) { REALLY_LONG_XML_SNIPPET} ....test code... end 

How to move REALLY_LONG_XML_SNIPPET to an external file?

+4
source share
1 answer

This is what I use in my specifications:

 let(:doc) { IO.read(Rails.root.join("spec", "fixtures", "api_response.xml")) } 

It will copy the contents of the file to a string.

Please note that I disabled the default ActiveRecord settings for RSpec, so instead I put my lights in this directory.

Update: with Rspec Rails 3.5 and later

can also use file_fixture

 let(:doc) { file_fixture("api_response.xml").read } 

for

files stored in spec / fixtures / files by default

but the file location can be customized.

+8
source

Source: https://habr.com/ru/post/1392543/


All Articles