Test methods using gon with rspec

I have a function that sends a variable to js using gon.

def calc_foo
  # calculate foo
  gon.foo = foo
end

I want to check this feature. Verify that the method returns the correct value using rspec.

it "should return bar" do
  foo = @foo_controller.calc_foo
  expect(foo).to eq(bar)
end

But I get the following error message when the test case reaches the line where the variable is sent to gon.

Failure/Error: foo = @foo_controller.calc_foo
 NoMethodError:
   undefined method `uuid' for nil:NilClass

I checked the value for foo and it is not Nil, so gon should be Nil. I believe that the mistake is that I am not speaking correctly. This is the rspec part of my gemfile

#rspec-rails includes RSpec itself in a wrapper to make it play nicely with Rails. 
#Factory_girl replaces Rails’ default fixtures for feeding test data
#to the test suite with much more preferable factories.
group :development, :test do
  gem 'rspec-rails'
  gem 'factory_girl_rails'
  gem 'capybara'
  gem 'gon'
end

So how can I make rspec play well with gon? (I also tried to include gon in my spec file without success)

+4
source share
2 answers

, gon .

- , gon.map_markers = [...]

JSON regexp (.split() match_array ):

....

# match something like
#   gon.map_markers=[{"lat":a,"lng":b},{"lat":c,"lng":d},...];
# and reduce/convert it to
#   ['"lat":a,"lng":b',
#    '"lat":c,"lng":d',
#    ...
#   ]
actual_map_markers = response.body
                     .match('gon.map_markers=\[\{([^\]]*)\}\]')[1]
                     .split('},{')

expect(actual_map_markers).to match_array expected_map_markers
+1

( gon ) :

RSpec.describe ThingiesController do
  let(:gon) { RequestStore.store[:gon].gon }

  describe 'GET #new' do
    it 'gonifies as expected' do
      get :new, {}, valid_session # <= this one
      expect(gon['key']).to eq :value
    end
  end
end

controller action gon - (, gon - ApplicationController), :

RSpec.describe ApplicationController do
  let(:gon) { RequestStore.store[:gon].gon }

  controller do
    # # Feel free to specify any of the required callbacks,
    # # like
    # skip_authorization_check
    # # (if you use `CanCan`) 
    # # or
    # before_action :required_callback_name

    def index
      render text: :whatever
    end
  end

  describe '#gon_related_method' do
    it 'gonifies as expected' do
      get :index
      expect(gon['key']).to eq :value
    end
  end
end

controller request/integration , gon , .

, , ( shared_examples, controller). issue, ( , ).

+1

All Articles