简体   繁体   中英

How to stub/mock original_filename method in Rails using Test::Unit

I am writing a test for file download during which I am using the original_filename. I was able to mock the file upload using fixture_file_upload . But how to stub/mock the original_filename call.

def import_for_photo(picture_url, user)
  remote_photo = open(picture_url)
  remote_photo.original_filename = "#{user.id}.jpg"
  user.update_attributes({:picture => remote_photo})
end

The test

def test_import_for_photo
  fixture_file = fixture_file_upload(File.join('files', 'test.jpg'), 'image/jpeg')
  OpenURI.expects(:open_uri).returns(fixture_file)
  import_for_photo("http://dummy_url.com/dummy.jpg", users(:one))
  assert_equal "1.jpg", users(:one).reload.picture_file_name
end

Test output,

NoMethodError: undefined method `original_filename=' for #<File:/tmp/test.jpg20120512-4253-x673nc-0>

I know why this test fails, but how to fix it ?

You should look in to using mocha for doing stubbing, or better yet (in my opinion) switch over to using rspec-rails. They have great mocking/stubbing facilities, and they allow you to make better tests, use cleaner syntax, and give more organization to your test file structure.

Each of these gems have readily available documentation about how to mock/stub out calls.

Found out the solution. Instead of trying to stub :original_filename , I stubbed :original_filename= (notice the '=') and my problem was solved !

Here is the code

def test_import_for_photo
  fixture_file = fixture_file_upload(File.join('files', 'test.jpg'), 'image/jpeg')
  fixture_file.expects(:original_filename=)
  OpenURI.expects(:open_uri).returns(fixture_file)
  import_for_photo("http://dummy_url.com/dummy.jpg", users(:one))
  assert_equal "1.jpg", users(:one).reload.picture_file_name
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM