nilify_blanks icon indicating copy to clipboard operation
nilify_blanks copied to clipboard

Cannot call rspec nilify_blanks on STI models

Open armchairdj opened this issue 6 years ago • 1 comments

I changed one of my tables into an STI table so I could subclass my Post model into Article, Review and MicroBlog. Immediately, the following test started failing:

describe "nilify_blanks" do
  it { is_expected.to nilify_blanks(before: :validation) }
end

This despite the following in my ApplicationRecord class:

class ApplicationRecord < ActiveRecord::Base
  ...
  nilify_blanks before: :validation
  ...
end

At first I thought it was because of some Rails internal doing something strange to the type attribute because it's STI. But then I discovered this works:

describe "nilify_blanks" do
  # Must specify individual fields for STI models.
  it { is_expected.to nilify_blanks_for(:alpha,   before: :validation) }
  it { is_expected.to nilify_blanks_for(:body,    before: :validation) }
  it { is_expected.to nilify_blanks_for(:slug,    before: :validation) }
  it { is_expected.to nilify_blanks_for(:summary, before: :validation) }
  it { is_expected.to nilify_blanks_for(:title,   before: :validation) }
  it { is_expected.to nilify_blanks_for(:type,    before: :validation) }
end

So I can use the nilify_blanks_for matcher on the STI type field and every other text/string field in the model. But when I use the nilify_blanks matcher, boom.

This is the failure before my change:

1) Post concerns behaves like an_application_record included nilify_blanks should nilify blanks [:before, :validation] and [:types, [:string, :text, :citext]]
   Failure/Error: it { is_expected.to nilify_blanks(before: :validation) }
     expected to nilify blanks {:before=>:validation, :types=>[:string, :text, :citext]}

This is a bummer because I went from being able to test nilify_blanks in a shared example for ApplicationRecord that's included in every model spec, to having to test it individually in just this one random model. The nilify_blanks matcher still works on all my non-STI models.

Any thoughts?

Thanks so much for an amazing gem that I use on every project.

armchairdj avatar Jul 16 '18 19:07 armchairdj

I suspect this may have been solved with some recent internal restructuring that is more resilient to subclassing. Please check if just-pushed v1.4.0 solves your issue. If not, if you can present a fully-formed example demonstrating the problem, I can look into a workaround. Indeed some of that matcher stuff is tricky given the lazy-loading of attribute methods by Rails.

rubiety avatar Apr 19 '20 01:04 rubiety