我有一个函数,它在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。这是rspec-我的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那么,我如何才能让rspec很好地使用gon呢?(我也曾尝试在我的spec-file中包含gon,但没有成功)
发布于 2015-11-24 00:11:45
在控制器规范( 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如果您不愿意在gon-related规范中使用特定的controller或action (假设您的ApplicationController中有一个gon-related方法),您可以使用Anonymous controller方法:
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在那里运行得很好。
但是,我仍然有一个与您类似的问题,尽管情况有所不同(从controller规范中包含的shared_examples发出请求)。我已经打开了相关的issue,请随时加入对话(对于任何感兴趣的人)。
发布于 2014-10-23 21:19:37
我测试了控制器是否在请求规范中向gon传递了正确的内容。
控制器设置一个对象数组--例如,gon.map_markers = [...]
我的请求规范通过regexp提取JSON ( .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_markershttps://stackoverflow.com/questions/24996388
复制相似问题