Ruby-on-rails – How to call the create action from the controller in RSpec

factory-botrspecruby-on-rails

I have a controller create action that creates a new blog post, and runs an additional method if the post saves successfully.

I have a separate factory girl file with the params for the post I want to make. FactoryGirl.create calls the ruby create method, not the create action in my controller.

How can I call the create action from the controller in my RSpec? And how would I send it the params in my factory girl factories.rb file?

posts_controller.rb

def create
  @post = Post.new(params[:post])
  if @post.save
    @post.my_special_method
    redirect_to root_path
  else
    redirect_to new_path
  end
end

spec/requests/post_pages_spec.rb

it "should successfully run my special method" do
  @post = FactoryGirl.create(:post)
  @post.user.different_models.count.should == 1
end

post.rb

def my_special_method
  user = self.user
  special_post = Post.where("group_id IN (?) AND user_id IN (?)", 1, user.id)
  if special_post.count == 10
    DifferentModel.create(user_id: user.id, foo_id: foobar.id)
  end
end   

end

Best Answer

Request specs are integration tests, using something like Capybara to visit pages as a user might and perform actions. You wouldn't test a create action from a request spec at all. You'd visit the new item path, fill in the form, hit the Submit button, and then confirm that an object was created. Take a look at the Railscast on request specs for a great example.

If you want to test the create action, use a controller spec. Incorporating FactoryGirl, that would look like this:

it "creates a post" do
  post_attributes = FactoryGirl.attributes_for(:post)
  post :create, post: post_attributes
  response.should redirect_to(root_path)
  Post.last.some_attribute.should == post_attributes[:some_attribute]
  # more lines like above, or just remove `:id` from
  #   `Post.last.attributes` and compare the hashes.
end

it "displays new on create failure" do
  post :create, post: { some_attribute: "some value that doesn't save" }
  response.should redirect_to(new_post_path)
  flash[:error].should include("some error message")
end

These are the only tests you really need related to creation. In your specific example, I'd add a third test (again, controller test) to ensure that the appropriate DifferentModel record is created.

Related Topic