Background: I have a Book
model with a cover_file
attribute that gets set with an uploaded file via one of my Rails controllers. I'm using Rails v4.0.4.
Goal: I want to test that only files with certain content types get saved. I plan to create Rspec test examples with ActionDispatch::Http:UploadedFile
objects set with different content_type
attributes.
Problem: When I initialize a new ActionDispatch::Http::UploadedFile
with a content_type
, it doesn't seem to get set (see test & output below that confirms that it's nil). It seems that I can only set it with a setter AFTER the UploadedFile has been initialized. I don't see any mention of this behavior in the docs nor could I find a similar Q&A on SO, so I'd appreciate anyone's help in determine what I'm doing wrong. Thanks!
Code:
describe Book do
let(:book) {FactoryGirl.build(:book)}
describe "Save" do
context "with valid data" do
before do
cover_image = File.new(Rails.root + 'spec/fixtures/images/cover_valid.jpg')
book.cover_file = ActionDispatch::Http::UploadedFile.new(tempfile: cover_image, filename: File.basename(cover_image), content_type: "image/jpeg")
puts book.cover_file.content_type.nil?
book.cover_file.content_type = "image/jpeg"
puts book.cover_file.content_type
end
specify{expect(book.save).to be_true}
end
end
end
Output:
true
image/jpeg