我有一个函数,在gon的帮助下将变量发送到js.
def calc_foo
# calculate foo
gon.foo = foo
end
我想测试这个函数,即确保方法使用rspec返回正确的值.
it "should return bar" do
foo = @foo_controller.calc_foo
expect(foo).to eq(bar)
end
但是,当测试用例到达变量发送到gon的行时,我收到以下错误消息.
Failure/Error: foo = @foo_controller.calc_foo
NoMethodError:
undefined method `uuid' for nil:NilClass
我检查了foo的值,它不是Nil,所以gon必须是Nil.
我认为错误是我没有正确地使用gon.这是我的Gemfile的rspec部分
#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
那么我怎样才能让rspec与gon很好地玩?
(我也尝试在我的spec文件中包含gon但没有成功)
最佳答案 我测试控制器在请求规范中将正确的东西传递给gon.
控制器设置一个对象数组 – 例如,gon.map_markers = […]
我的请求规范通过regexp提取JSON(.split()和match_array处理order-independent-array-ness):
....
# 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