Question

I want to use a rake task to seed some user data in my database for manual testing. Because of the complexity of my tables and business logic, the easiest way for me to do this would be to execute POSTs to my user_controller from the rake task. With RSpec (and FactoryGirl) I can do

   describe "POST create" do
        it "registers a new user" do
            @request.env["devise.mapping"] = Devise.mappings[:user]
            user = attributes_for(:user)
            response = post( :create, user: user)
            response.status.should eql(200)
        end
    end

How can I use the 'post' helper in my rake task?

Was it helpful?

Solution

create a lib/tasks/seed_post.rake the name of the file doesn't matter

and put the following code in it

namespace :seed do
  task :posts => :environment do
    50.times do |i|
      # it's your own problem to generate the following user, params so that it works
      Post::CreationService.perform(user, params)
    end
  end
end

now you can call the task using.. rake seed:posts or zeus rake seed:posts or bundle exec rake seed:posts depending whether you are using zeus or bundler or whatever...

what really matters is that your call should be in the form of

rake namespace_you_defined:task_name_you_defined

also you have to change the controller create to become

def create
  @post = Post::CreationService.perform(current_user, post_params)
  # instead of this old code i'm assuming you are using
  @post = current_user.posts.create!(post_params)
  ...
end

also add a this file

# app/services/post/creation_service.rb
class Post::CreationService
  def self.perform(current_user, params)
    current_user.posts.create!(params)
   end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top