0

I am creating a TextMessage model to manage communications. I am using shoulda-matchers' for testing

my model

class TextMessage < ApplicationRecord
  validates :message, presence: true
end

Now my test

RSpec.describe TextMessage, type: :model do
  subject { FactoryBot.create(:text_message) }
  it { is_expected.to validate_presence_of :message }
end

I am able to run FactoryBot.create(:text_message) on the console to create a text message without any problems. But when I run my test sweet I get this error

TextMessage
  is expected to validate that :message cannot be empty/falsy (FAILED - 1)

Failures:

  1) TextMessage is expected to validate that :message cannot be empty/falsy
     Failure/Error: self.message = message.gsub("\u0000", '')

     NoMethodError:
       undefined method `gsub' for nil:NilClass
Schwern
  • 153,029
  • 25
  • 195
  • 336
MZaragoza
  • 10,108
  • 9
  • 71
  • 116
  • 1
    Can you show your text_message factory, please? And the stack trace of the error, where is the `self.message = message.gsub("\u0000", '')` line? – Schwern Nov 02 '20 at 18:37
  • Works For Me™. You probably have something that normalizes attributes which is trying to strip null bytes. – Schwern Nov 02 '20 at 18:47
  • @Schwern Thanks you so much. I was able to change `self.message = message.gsub("\u0000", '')` to `self.message = message.to_s.gsub("\u0000", '')` this maked the test pass – MZaragoza Nov 02 '20 at 19:15
  • 1
    That will change a `nil` into an empty string which may be important. To avoid altering the data in unexpected ways use [the safe navigation operator `&.`](https://rubyinrails.com/2017/11/17/safe-navigation-operator-ampersand-dot-in-ruby/). `self.message = message&.gsub("\u0000", '')`. – Schwern Nov 02 '20 at 19:56
  • Thanks I will do that change – MZaragoza Nov 02 '20 at 19:57

0 Answers0