Search code examples
ruby-on-railsruby-on-rails-5minitest

Where can I put test data that is not part of a model?


I want to test against a list of invalid email addresses. At the moment, they live in my setup method:

  def setup
    @invalid_email_addresses = [
      'plainaddress',
      '#@%^%#$@#$@#.com',
      '@domain.com',
      'Joe Smith <[email protected]>',
      'email.domain.com',
      'email@[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      'あいうえお@domain.com',
      '[email protected] (Joe Smith)',
      'email@domain',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]'
    ]
  end

This makes the method rather long. I would like to move them to a yml file:

# test/fixtures/email_addresses.yml
invalid_email_addresses:
    - 'plainaddress'
    - '#@%^%#$@#$@#.com'
    - '@domain.com'
    - 'Joe Smith <[email protected]>'
    - 'email.domain.com'
    - 'email@[email protected]'
    - '[email protected]'
    - '[email protected]'
    - '[email protected]'
    - 'あいうえお@domain.com'
    - '[email protected] (Joe Smith)'
    - 'email@domain'
    - '[email protected]'
    - '[email protected]'
    - '[email protected]'
    - '[email protected]'

But that results in an error for each test:

ActiveRecord::Fixture::FormatError: fixture key is not a hash: /Users/stefan_edberg/Rails/tennis_app/test/fixtures/emaild_addresses.yml, keys: ["invalid_email_addresses"]

If not in fixtures, where should I put these email addresses?


Solution

  • The error shared itself conveys that there is some problem in parsing the YAML contents. I saved the following contents in a file test.yml on my Desktop

    # test/fixtures/email_addresses.yml
    invalid_email_addresses:
      - 'plainaddress'
      - '#@%^%#$@#$@#.com'
      - '@domain.com'
      - 'Joe Smith <[email protected]>'
      - 'email.domain.com'
      - 'email@[email protected]'
      - '[email protected]'
      - '[email protected]'
      - '[email protected]'
      - 'あいうえお@domain.com'
      - '[email protected] (Joe Smith)'
      - 'email@domain'
      - '[email protected]'
      - '[email protected]'
      - '[email protected]'
      - '[email protected]' 
    

    and then tried loading it from irb and it successfully loaded:

    enter image description here

    Please Note: Initially when I copied the YAML contents as it is in my file and tried loading it, I encountered parsing error and then I removed the following entry and tried again and the parse was successful

    - 'あいうえお@domain.com'`
    

    That entry contains Unicode characters. As YAML is indentation-sensitive copying that entry as it is in my file made the indentation inconsistent which caused parse error. Fixing the indentation for that entry made the parse successful.