Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rspec populating a variable with data from an external file

I'm still new top rspec, so please excuse if this is an easy one but I wasn't able to find an answer on Google. I have a library module that handles parsing some data from an API response. I have written tests, and all that works fine, however I'd like to move the fake API response data into an external file since it's pretty long and makes the test harder to read. I looked at fixtures and factories, but those are really for models, and this is just a really long xml snippet. My current test looks something like this

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

How can I move REALLY_LONG_XML_SNIPPET into an external file?

like image 561
Fitmo Appadmin Avatar asked Jan 23 '12 20:01

Fitmo Appadmin


1 Answers

This is what I use in my specs:

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

It will copy the file's contents into a string.

Note that I have turned off the default ActiveRecord fixtures for RSpec, so I put my fixtures in that directory instead.

Update: with Rspec Rails 3.5 and newer

one can also use file_fixture

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

for

files stored in spec/fixtures/files by default

but file location can be customized.

like image 189
James Avatar answered Nov 15 '22 00:11

James