Search code examples
ruby-on-railsrubyrspecreform

How to test that a form object includes a Form property?


I have a form object that looks like this:

class LeaderForm < UserForm
  feature Reform::Form::MultiParameterAttributes

  property :title
  property :gender
  property :phone_number
  property :date_of_birth, multi_params: true

  property :address, form: AddressForm # need to test this line

  validates :title, :gender, :phone_number, :date_of_birth, presence: true
end

How do I write a feature spec to test whether the AddressForm is present?

I already have a working spec to test the other "properties" (title, gender, etc.)

I've tried something like

it 'must have the address form present' do
  expect(form.address).to include(AddressForm)
end

The output of which is

  1) LeaderForm must have the address form present
       Failure/Error: expect(form.address).to include(AddressForm)

         expected #<AddressForm:0x007f89231c3280 @fields={"address1" => nil, "address2" => nil, "address3" => nil, "city" => ni...odel::Errors:0x007f89231c2b50 @base=#<AddressForm:0x007f89231c3280 ...>, @messages={}, @details={}>> to include AddressForm, but it does not respond to `include?`
         Diff:
         @@ -1,2 +1,41 @@
         -[AddressForm]
         +#<AddressForm:0x007f89231c3280
         + @_changes={},
         + @errors=
         +  #<Reform::Form::ActiveModel::Errors:0x007f89231c2b50
         +   @base=#<AddressForm:0x007f89231c3280 ...>,
         +   @details={},
         +   @messages={}>,
         + @fields=
         +  {"address1"=>nil,
         +   "address2"=>nil,
         +   "address3"=>nil,
         +   "city"=>nil,
         +   "postal_code"=>nil,
         +   "country"=>nil},

Which seems to me like it's almost there but not quite.

I am very new to RSpec in general so sorry if I haven't provided enough information.


Solution

  • I think you're looking for be_a:

    it 'must have the address form present' do
      expect(form.address).to be_a(AddressForm)
    end
    

    RSpec maps an unknown matcher beginning with be_, like be_foo, to a method like is_foo?. You could also write (less nicely)

    it 'must have the address form present' do
      expect(form.address.is_a? AddressForm).to be true
    end