Coda Chang Coda Chang - 1 month ago 18
Ruby Question

Rails Rspec test with carrierwave image

I wrote an API which can return latest 5 Newsletter and its image, but I am stuck at writing its

rspec
test.

First of all, here is the relationship between model.

Newsletter has_many NewsletterImages
NewsletterImage belong_to Newsletter


Secondly, I thought that I need to create some data in test database, so I wrote following code in
rspec
file.

7.times do |i|
n = Newsletter.create(title: "Test#{i}", content: "TestContents#{i}")
2.times do |i|
ni = NewsletterImage.create(newsletter_id: n.id, order: i)
ni.image = File.open('xxx.png')
ni.save
end
end


So, I need to upload file in very test? Is there a better way to generate data and test?

Answer

Better to use Factory Girl to make your test data. That way, you can write clean tests like

# /spec/factories/newsletter_factory.rb
FactoryGirl.define do
  factory :newsletter do
    title "My newsletter"
    content "Some content"
  end
end

# /spec/factories/newsletter_image_factory.rb
FactoryGirl.define do
  factory :newsletter_image do
    newsletter
    image fixture_file_upload( Rails.root + 'spec/fixtures/images/example.jpg', "image/jpg")
  end
end

# spec/models/newsletter_spec.rb
image = create :newsletter_image
expect(image.newsletter.title).to eq 'My Newsletter'

With all of the details of how the models are created hidden in the factory definition files, it's then easy to share the code across many tests.

For more detail about adding carrierwave files to Factory Girl definitions, look for other answers such as this one: http://stackoverflow.com/a/9952914/693349

Comments