RSpec: Problems converting to the new "allow" syntax for mocks/stubs - ruby-on-rails-4

I am trying to learn rspec and apply what I am learning to an existing rails app.
I am trying to create a mock of a user called "current_user"
I have basically taken this line of code
controller.stub(:current_user).and_return(build_stubbed(:user))
and placed it before my tests (all of which require a current_user to be defined)
This works. But
I know that this syntax is deprecated and I should be using
allow().to receive().and_return()
syntax but I can't seem to convert it to the new syntax and get it to work.
I tried
user = double("user")
allow(user).to receive(:current_user).and_return(build_stubbed(:user))
without success. I reality I have no idea what I am doing with this and need to be pointed in the right direction. I have looked extensively for an answer but I suspect this is too basic.
Would appreciate some guidance.

Currently, you're stubbing the current_user method for your controller variable. In your new syntax example, you've put the stub on the user double object.
Without knowing more about build_stubbed, I would expect it to look like:
allow(controller).to receive(:current_user).and_return build_stubbed(:user)

Related

when do you use getGraphObject and getGraphEdge

I'm working on a php based site and integrating some facebook sdk into it to get some basic user information. One thing I've been running into is, when I make a request to the graph, how do I know if I should be using getGraphObject or getGraphEdge? I'm not seeing anything intuitive yet to tell me that.
I'm running the php-sdk4 -> version 5
Here's one example that I ran into last night..
$response = $fb->get('/me/friends', $fbToken);
$fbfriends = $response->getGraphEdge()->asArray();
In the documentation, if you look at the php example, they use getGraphObject. But when I use it, I get an error telling me I should probably use the Edge. There are a lot of "get" functions, but I don't see anything that tells me how to know what to use. getGraphObject, getGraphEdge, getGraphUser, etc. I'd love some insight into this one, because it's been a guessing game for me.
Basicly, when:
Getting /{node-id}, you should use getGraphNode() (getGraphObject() is deprecated)
Getting /{node-id-with-known-type}, you should use getGraph{Type}().
For example, getting /me then use getGraphUser(), getting /{event-id} then use getGraphEvent()
Getting /{node-id}/{edge-name}, you should use getGraphEdge() (getGraphList() is deprecated)
Getting /{node-id}/{edge-name-with-children-known-type}, you should use getGraphEdge({children-type-class}).
For example, getting /me/albums then use getGraphEdge('GraphAlbum')
Nodes class name are in Facebook\GraphNodes namespace.

Mongoid 4 finding embedded documents by ID

I have a project that is my first serious dive into Mongoid.
I saw a tip to use the following command:
Parent.where('childrens._id' => Moped::BSON::ObjectId(params[:id])).first
But this doesn't work. Error message was:
NameError: uninitialized constant Moped::BSON
I found that BSON is no longer included, so I added it to my Gemfile, as well as Moped. Then, I did another fix I found (placing Moped::BSON=BSON in application.rb).
This still didn't work, but the error changed to:
NoMethodError: undefined method `ObjectId' for BSON:Module
So I am assuming that this method got deprecated or something. Does anyone have any other tips?
Just to be clear, I am finding myself in the situation where I want to sort embedded documents using jquery-sortable. This requires me to update them in the database, but the serialize from that doesn't include the parent document in the hash. So I figured I'd try to get it on the back end using an ID from the embedded document. That is why I need it.
Thanks again for any help you can provide.
Try simply:
Parent.where('childrens._id' => params[:id]).first
I have solved the question though this won't be of much help to people in the future. The requirements have changed and now I am using human-readable strings as IDs to assist in friendly URLs and some other stuff.
Therefore, I don't have any issues with ObjectIds. Cortex's solution should (from what I have read) work for dealing with ObjectIds but I cannot verify it now.

Django Rest Framework: is it possible to modify a Serializer class at runtime?

I see I can easily modify the Meta options of a Serializer at run time (i'm not even sure this is the right way to call it, I read around somebody call it monkey patching, even though i don't like it):
NodeDetailSerializer.Meta.fields.append('somefield')
What if I need to do something like:
NodeDetailSerializer.contact = serializers.HyperlinkedIdentityField(view_name='api_node_contact', slug_field='slug')
NodeDetailSerializer.Meta.fields.append('contact')
Why would I need to do that?
I'm trying to build a modular application, I have some optional apps that can be added in an they automatically add some features to the core ones.
I would like to keep the code of the two apps separate, also because the additional applications might be moved in a different repository.
Writing modular and extensible apps is really a tricky business.
Would like to know more about that if anybody has some useful resources to share.
Federico
I found a solution for my problem.
My problem was: I needed to be able to add hyperlinks to other resources without editing the code of a core app. I needed to do it from the code of the additional module.
I wrote this serializer mixin: https://gist.github.com/nemesisdesign/8132696
Which can be used this way:
from myapp.serializers import MyExtensibleSerializer
MyExtensibleSerializer.add_relationship(**{
'name': 'key_name',
'view_name': 'view_name_in_urls_py',
'lookup_field': 'arg_passed_to_to_view_name'
})

RESTful API and Foreign key handling for POSTs and PUTs

I'm helping develop a new API for an existing database.
I'm using Python 2.7.3, Django 1.5 and the django-rest-framework 2.2.4 with PostgreSQL 9.1
I need/want good documentation for the API, but I'm shorthanded and I hate writing/maintaining documentation (one of my many flaws).
I need to allow consumers of the API to add new "POS" (points of sale) locations. In the Postgres database, there is a foreign key from pos to pos_location_type. So, here is a simplified table structure.
pos_location_type(
id serial,
description text not null
);
pos(
id serial,
pos_name text not null,
pos_location_type_id int not null references pos_location_type(id)
);
So, to allow them to POST a new pos, they will need to give me a "pos_name" an a valid pos_location_type. So, I've been reading about this stuff all weekend. Lots of debates out there.
How is my API consumers going to know what a pos_location_type is? Or what value to pass here?
It seems like I need to tell them where to get a valid list of pos_locations. Something like:
GET /pos_location/
As a quick note, examples of pos_location_type descriptions might be: ('school', 'park', 'office').
I really like the "Browseability" of of the Django REST Framework, but, it doesn't seem to address this type of thing, and I actually had a very nice chat on IRC with Tom Christie earlier today, and he didn't really have an answer on what to do here (or maybe I never made my question clear).
I've looked at Swagger, and that's a very cool/interesting project, but take a look at their "pet" resource on their demo here. Notice it is pretty similar to what I need to do. To add a new pet, you need to pass a category, which they define as class Category(id: long, name: string). How is the consumer suppose to know what to pass here? What's a valid id? or name?
In Django rest framework, I can define/override what is returned in the OPTION call. I guess I could come up with my own little "system" here and return some information like:
pos-location-url: '/pos_location/'
in the generic form, it would be: {resource}-url: '/path/to/resource_list'
and that would sort of work for the documentation side, but I'm not sure if that's really a nice solution programmatically. What if I change the resources location. That would mean that my consumers would need to programmatically make and OPTIONS call for the resource to figure out all of the relations. Maybe not a bad thing, but feels like a little weird.
So, how do people handle this kind of thing?
Final notes: I get the fact that I don't really want a "leaking" abstaction here and have my database peaking thru the API layer, but the fact remains that there is a foreign_key constraint on this existing database and any insert that doesn't have a valid pos_location_type_id is raising an error.
Also, I'm not trying to open up the URI vs. ID debate. Whether the user has to use the pos_location_type_id int value or a URI doesn't matter for this discussion. In either case, they have no idea what to send me.
I've worked with this kind of stuff in the past. I think there is two ways of approaching this problem, the first you already said it, allow an endpoint for users of the API to know what is the id-like value of the pos_location_type. Many API's do this because a person developing from your API is gonna have to read your documentation and will know where to get the pos_location_type values from. End-users should not worry about this, because they will have an interface showing probably a dropdown list of text values.
On the other hand, the way I've also worked this, not very RESTful-like. Let's suppose you have a location in New York, and the POST could be something like:
POST /pos/new_york/
You can handle /pos/(location_name)/ by normalizing the text, then just search on the database for the value or some similarity, if place does not exist then you just create a new one. That in case users can add new places, if not, then the user would have to know what fixed places exist, which again is the first situation we are in.
that way you can avoid pos_location_type in the request data, you could programatically map it to a valid ID.

Django: assign accesskey to label instead of select

i'm developing a site that must be as accessible as possible. While assigning the accesskeys to my form fields with
widget=FieldWidget(attrs={'accesskey':'A'})
i found out that the w3c validator won't validate an xhtml strict page with an accesskey in a select tag. Anyway i couldn't find a way to assign an accesskey to the label related to the select field (the right way to make the select accessible). Is there a way to do so?
Thanks
Interesting question. HTML 4.01 also prohibits accesskey in a select.
I believe the Short Answer is: Not in standard Django.
Much longer answer: I looked at the code in django/forms/fields.py and .../widgets.py and the label is handled strictly as a string (forced to smart_unicode()). Four possible solutions come to mind, the first three are not pretty:
Ignore the validation failure. I hate doing this, but sometimes it's a necessary kludge. Most browsers are much looser than the DTDs in what they allow. If you can get the accesskey to work even when it's technically in the wrong place, that might be the simplest way to go.
Catch the output of the template and do some sort of ugly search-and-replace. (Blech!)
Add new functionality to the widgets/forms code by MonkeyPatching it. MonkeyPatch django.forms.fields.Field to catch and save a new arg (label_attrs?). MonkeyPatch the label_tag() method of forms.forms.BoundField to deal with the new widget.label_attrs value.
I'm deliberately not going to give more details on this. If you understand the code well enough to MonkeyPatch it, then you are smart enough to know the dangers inherent in doing this.
Make the same functional changes as #3, but do it as a submitted patch to the Django code base. This is the best long-term answer for everyone, but it's also the most work for you.
Update: Yoni Samlan's link to a custom filter (http://www.djangosnippets.org/snippets/693/) works if you are generating the <label> tag yourself. My answers are directed toward still using the full power of Forms but trying to tweak the resultant <label>.