我正在为application_controller.rb中的方法编写测试,并且无法编写正确的测试。该应用程序基于Rails 3.2.17。
object.rb
def previously_purchased?
return JSON.parse(self.features)['key']['previously_purchased'] if self.features
end
application_controller.rb
def include_bar?
url_param = params[:keyword] || cookies[:keyword]
@keyword_object = Object.find_by_url(url_param)
if @keyword_object.previously_purchased? && !cookies[:prior_purchase]
@keyword_object = nil
return
end
end
factories.rb
factory: object do
url_param 'TEST'
end
application_controller_spec.rb
#this was the most recent test I tried
context 'URL parameter keyword is present or keyword cookie is present' do
context 'object is displayed only to previously purchased' do
before(:each) do
@saved_object = create :object
@other_object = JSON.parse(@saved_object.features)
@other_object['key']['previously_purchased'] = true
@new_object = @other_object.to_json
request.cookies[:prior_purchase] = 'sub'
get :index
end
it 'finds object' do
expect(assigns(:keyword_object)).to be_nil
end
end
end
这会返回以下错误
Failure/Error: @other_object = JSON.parse(@saved_nanobar.features)
TypeError: no implicit conversion of nil into String
这是有道理的,因为我无法将之前的值设置为true。
我也试过
context 'object is displayed only to previously purchased' do
before(:each) do
@saved_object = create :object
@saved_object.features['key']['previously_purchased'] = true
request.cookies[:prior_purchase] = 'sub'
get :index
end
it 'finds object' do
expect(assigns(:keyword_object)).to be_nil
end
end
Failure/Error: @saved_object.features['key']['previously_purchased'].to_json = true
NoMethodError: undefined method
[]'为零:NilClass`
我有点理解,但不足以修复我的测试。我可能在形成和写出我的问题时遗漏了一个结尾或其他语法,所以请耐心等待。
这一直困扰着我,我很感激任何帮助。我无法找到资源来帮助我进一步指导。如果您需要我修改/澄清我的问题或需要更多信息,请告诉我,我会对此有所了解。
答案 0 :(得分:0)
您的object.features
需要包含JSON。像这样设置你的对象:
@saved_object = create(
:object, features: "{ \"key\": { \"previously_purchased\": true} }"
)
答案 1 :(得分:0)
如果列保存为JSON,您应该使用serialize
,这将处理所有混乱:
model = MyModel.new
model.features = { key: { previously_purchased: true } }
model.save
然后您可以将其作为任何其他结构进行操作,而无需手动de或重新序列化:
def previously_purchased?
if (self.features)
!!self.features.dig('key', 'previously_purchased')
else
false
end
end
然后你可以这样做:
!!
使用双重否定(//.each because there can be multiple thumbnails in case of multiple uploads
$('img[data-dz-thumbnail]').each(function(i, img){
var imgSrc = $(this).attr('src');
console.log(imgSrc);
});
)强制该值作为布尔值以及Ruby 2.3.1 dig
方法来导航哈希值。