Search code examples
ruby-on-railsrspecfactory-botguard

How to lint factories immediately with guard and factory girl?


What do I need to put in my Guardfile (in a Rails application with RSpec and FactoryGirl) to lint all my factories every time I change a factory?

I know that it is possible to run all models spec, accordingly to this question: Using guard-rspec with factory-girl-rails, but I want to only lint them all.

I tried to do this in Guardfile, but it was not enough:

watch(%r{^spec/factories/(.+)\.rb$}) {
  FactoryGirl.lint
}

Thanks in advance.


Solution

  • It's clear what you want to do, but it won't work that way.

    Guard doesn't run "within" the application. It runs RSpec as a process. Calling FactoryGirl.lint is called within Guard, and not within the RSpec process (which is what you want).

    The "trick" here would be to create a "fake" spec file that does nothing except linting, so you can then do:

    guard :rspec do
      watch(%r{^spec/factories/(.+)\.rb$}) { 'spec/linting_spec.rb' }
    end
    

    Here's how it works:

    1. Whenever a factory file changes, Guard launches Guard::RSpec with the 'spec/linting_spec.rb' (or whatever you name it).
    2. Guard::RSpec just calls rspec spec/linting_spec.rb.

    So as long as rspec spec/linting_spec.rb works like you want, you can then "plug" that into guard like above.

    spec/linting_spec.rb can have just one "fake" RSpec test for a model - just enough so that the linting is triggered.

    That way you'll have just the linting - and without running any model tests.