You cannot simply run ruby lib/tasks/test.rb
because the Rails environment will not be loaded. To fix this, you need to use a rake task.
You first have to rename your file lib/tasks/test.rb
to lib/tasks/test.rake
.
Then, you need to add this to test.rake
.
namespace :contact do # This is not require. It can work without having to nest your task within a namespace.
desc 'Add contact'
task 'add' => [:environment] do #Here, we specify we want to load the environment
Contact.create({:name => "Josh", :phone => "123-456789"})
end
end
Then, run rake -T
which will list all the available tasks.
You will be able to launch your task with rake contact:add
.
To schedule your task to be run at a specific time, you might want to take a look at the Whenever gem.
Hope it helps.