Instead of returning a single User via users(:id), is there a way to get all of the users defined in users.yml?
In rspec this seems to be users(:all), but that just looks for a user with id == all in Minitest.
If you haven't created any additional users in your test, you can simply call the following:
User.all
Related
In my db.py file I have defined a table called recipe with a field as Field('cook','string',default=auth.user.username) which basically creates a recipe with an uploaded image and username. It works fine but whenever I logout I get an error saying ('NoneType' object has no attribute 'username')
auth.user is None when the user is not logged in, so you cannot try to access the .username attribute in that case. To avoid the problem, just add some conditional logic:
default=auth.user.username if auth.user else None
I'm looking to load a single (chosen randomly) object from a single table in my database on every page of my rails app.
For example, a quotes table which has several quotes in the table, and I just want one on every page load.
What's the best way to accomplish this? Obviously copy & pasting the query into each controller isn't the right way to go about this.
I wouldn't use before_filter for this, there is no need to access database on redirecting actions and other "not rendered" actions. Instead I would use helper_function, and I would call it in the layout, as you need to position it anyways.
def random_quote
#quote ||= "Select random quote here"
end
helper_method :random_quote
Your method of selecting a quote is up to you. You just need to access random_quote as a normal helper method in the layout. This only access one quote per action, only if the layout is rendered.
This kind of stuff typically goes into a before_filter in the ApplicationController :
before_filter :get_random_quote
#This code is executed before every action of your app
def get_random_quote
random_id = ...#Generate a random ID ...
#random_quote = Quote.find(random_id)
end
Then in your views, just refer to #random_quote. Done!
Edit : on second thought, Matzi solution seems smarter. The request will only get called when you actually output something. Nothing's wasted.
Assuming PostgreSQL:
before_filter :get_quote
def get_quote
#quote = Quote.order('RANDOM()').limit(1)
end
Currently my URL's appear as www.website.com/entries/1, I'd like to make them appear as www.website.com/title-of-entry. I've been messing around with routes and have been able to get the entry title to display in the URL, but Rails is unable to find the entry without supplying an ID. If I send the ID along with the parameters, the URL appears as www.website.com/title-of-entry?=1. Is there anyway I can pass the ID without having it appear in the URL as a parameter? Thanks!
Like most things, there's a gem for this.
FriendlyID.
Installation is easy and you'll be up and running in minutes. Give it a whirl.
Ususally you'll want to to save this part in the database title-of-entry (call the field slug or something`). Your model could look something like this:
class Entry < ActiveRecord::Base
before_validation :set_slug
def set_slug
self.slug = self.title.parameterize
end
def to_param
self.slug
end
end
Now your generated routes look like this: /entries/title-of-entry
To find the corresponding entries you'll have to change your controller:
# instad of this
#entry = Entry.find(params[:id]
# use this
#entry = Entry.find_by_slug(params[:id])
Update
A few things to bear in mind:
You'll have to make sure that slug is unique, otherwise Entry.find_by_slug(params[:id]) will always return the first entry with this slug it encounters.
Entry.find_by_slug(params[:id]) will not raise a ActiveRecord::RecordNotFound exception, but instead just return nil. Consider using Entry.find_by_slug!(params[:id]).
If you really want your routes to look like this /title-of-entry, you'll probably run into problems later on. The router might get you unexpected results if a entry slug looks the same as another controller's name.
I want to write a test like the following:
account = Account.find(1)
#controller.should_receive(:authorize!).with(:create, instance_of(User, :account_id => account.id))
(exact example on testing the cancan gem on a controller of mine)
I know that the part :account_id => account.id is invalid.
My question goes here:
How can I call the instance_of but at the same time test the attributes of the instance to have specific values?
I hope that this is clear. Otherwise, let me know, how can I make it more clear.
Thanks in advance
Panayotis
What are you trying to test? That the controller loads the proper instance and the passes the proper instance to :authorize!? If yes, then something like :
Account.should_receive(:find).returns(account))
#controller.should_receive(:authorize!).with(account)
would do the job
You may use a block for more control on the expected arguments, more info:
Argument matchers
To expand on the accepted answer, it is possible to use argument matchers to do the following:
expect(controller).to receive(:authorize!).with do |symbol, received_user|
expect(symbol).to eq :create
expect(received_user).to be_a User
expect(received_user.account).to eq account
end
I have a Moderator model which basically queries web site related stat results from other models.
An e.g. of displayed stats could be the total number of users belonging to a particular area out of many areas in a city. Limiting the number of such records to a fixed number. For this, the body defined within the Moderator model makes use of an Area model.
Since the queries are not using anything from the same model, but actually from other models, there wasn't a need for me to have a table migration wrt this model.
I basically am now trying to test the defined methods in the Moderator model using Rspec.
What I am basically trying to test is that a call to the method should return success, this I am doing through:-
subject.send(:method_name)
response.should be_success
I'm getting a common error for all such defined methods saying that database_name.table_name does not exist. Well , this is true but how should is it really making a difference?, and how to get a work around for this to just test a simple use case of calling a method successfully in the above context.
Thanks.
Try something like this
describe Moderator do
it "should do something" do
moderator = Moderator.new
moderator.something.should == "do"
end
end
This assumes that you have a method something on Moderator and that it returns the string "do".
I think the RSpec Book provides great information and examples if you want to get more in-depth with your rspec.
Well,
The below line code did work for me:-
Model_name.method_name.should_not be_nil