Upgrade to Pro — share decks privately, control downloads, hide ads and more …

How to test Rails engine generator with RSpec

How to test Rails engine generator with RSpec

shinjuku.rb #26(2015/06/24)

B8e501d93b98a553abf0b5cee0c33503?s=128

yasaichi

June 24, 2015
Tweet

Transcript

  1. How to test Rails engine generator with RSpec shinjuku.rbɹ2015/06/24 @yasaichi

  2. About me [1] pry(main)> me => { twitter:'@_yasaichi', github: 'yasaichi',

    splatoon: nil, blog: 'http://web-salad.hateblo.jp' }
  3. ޷͖ͳঁੑΞΠυϧ ೫໦ࡔ46

  4. ಥવͰ͕͢ɺRails EngineͰ GemΛ࡞ͬͨ͜ͱ͋Δํʁ

  5. Ͱ͸ɺࣗ෼ͰGeneratorΛ ॻ͍ͨ͜ͱͷ͋Δํʁ

  6. Agenda • ͖͔͚ͬ • ओཁGemͰͷGeneratorʹର͢Δςετ • RspecΛ࢖ͬͯͲ͏ॻ͍͔ͨ • ײ૝ͱ·ͱΊ

  7. Background • ࠷ۙࣾ಺༻GemͷGeneratorΛॻ͍ͨ
 ex: rails g mygem:install • RSpecͰςετΛॻ͜͏ͱͨ͠Β৘ใ͕
 গͳͯۤ͘࿑ͨ͠

    • Ͳ͏΍ͬͯղܾ͔ͨ͠Λڞ༗͍ͨ͠
  8. ओཁGemͰ͸GeneratorΛ Ͳ͏ςετ͍ͯ͠Δͷ͔

  9. Overview Nothing Rspec + Gem Test::Unit airbrake doorkeeper rails_config ͳͲ

    draper devise
  10. RSpec + Gem • RSpec͸GeneratorͷςετΛඪ४Ͱ
 αϙʔτ͍ͯ͠ͳ͍ͷͰɺGemΛ࢖͏ • generator_spec, ammeterͷ2୒ʁ •

    ͲͪΒ΋GitHubͰ˒50͘Β͍Ͱɺ͋·Γ
 ੝Γ্͕ΓΛײ͡ΒΕͳ͍ ٩(๑`н´๑)۶
  11. Test::Unit • Rails::Generators::TestCaseͱ͍͏Ϋϥε͕
 σϑΥϧτͰ༻ҙ͞Ε͍ͯΔ • Test::UnitΛ࢖͍ͬͯΔͳΒ͜ΕͰOK • ͪͳΈʹɺgenerator_spec, ammeter͸
 ͜ΕΛ಺෦Ͱར༻͍ͯ͠Δ

  12. ݁ہͲ͏͔ͨ͠

  13. Use "ammeter" • generatorʢൃిػʣ㲗 ammeter ʢిྲྀܭʣ • generator_specͱൺֱͯ͠matcher͕ॆ࣮
 ͍ͯ͠Δ •

    ϝϯς͞Εͳ͘ͳͬͨΒDraper΋ಓ࿈Εʹ
 Ͱ͖Δͱ͍͏Ṗͷ҆৺ײ͕ܾΊखʹ
  14. Usage RSpec.describe MyGem::Generators::InstallGenerator, type: :generator do destination File.expand_path('../../tmp', __FILE__) before

    do prepare_destination # initialize ../../tmp end describe 'generated files' do before do run_generator # run "rails g my_gem:install" end # write test cases here end after(:context) do FileUtils.rm_rf(destination_root) end end
  15. Matchers # ଞʹ be_a_migration, have_method ͕͋Δ # ৄ͘͠͸ https://github.com/alexrothenberg/ammeter Λࢀরͷ͜ͱ

    describe 'generated files' do before do run_generator # run: rails g my_gem:install end describe 'config/initializers/my_gem.rb' do subject { file('config/initializers/my_gem.rb') } it { is_expected.to exist } it { is_expected.to have_correct_syntax } it { is_expected.to contain /\AMyGem\.configure do \|config\|/ } end end
  16. [IMO] • ༻ҙ͞Ε͍ͯΔmatcherΛ࢖͑͹΍Γ͍ͨ
 ͜ͱ͸͍͍ͩͨͰ͖ͯศར • ςετέʔεຖʹϑΝΠϧΛ࡞ͬͯ͸ফ͢Λ
 ܁Γฦ͢ͷ͕ͪΐͬͱؾʹͳΔ → จࣈྻͱͯ͠ग़ྗͯ͠த਎͚ͩݕ͍ࠪͨ͠

  17. Conclusion • Test::UnitΛ࢖͑͹Ϩʔϧʢ˞ʣʹ৐ΕΔ
 ˞ Rails::Generators::TestCase • RSpec͸GeneratorͷςετΛඪ४Ͱαϙʔτ ͍ͯ͠ͳ͍ͷͰɺGemΛ࢖͏͜ͱʹͳΔ • GemͷதͰ͸ammeter͕͍͍ײ͡

  18. Happy testing with RSpec!