Horatio Rosa Horatio Rosa - 1 month ago 5
Ruby Question

Rspec Rails setting a value in a JSON object

I am writing a test for a method in my application_controller.rb and having trouble writing a proper test. The app is built on 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


this returns the following error

Failure/Error: @other_object = JSON.parse(@saved_nanobar.features)


TypeError: no implicit conversion of nil into String


which makes sense, in a way as I wasn't able to set the value previously_purchased to true.

I also tried

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
[ ]' for nil:NilClass`

Which I kind of understand but not well enough to fix my test. I may have left out an end or some other syntax in forming and writing my question, so kindly have patience with those.

This has been blocking me for to long and I'd appreciate any help. I was unable to find resources to help guide me further. If you need me to modify/ clarify my question or need more info, let me know and I'll get right on it.

Answer

Your object.features needs to contain a JSON. Setup your object like this:

@saved_object = create(
  :object, features: "{ \"key\": { \"previously_purchased\": true} }"
)