What is the proper way to test 'create' controller actions? - ruby-on-rails

I am using Ruby on Rails 3.2.2, Rspec 2.9.0 and RspecRails 2.9.0. I would like to test the create controller action but I don't know how to make that the "right"/"proper" way. I "scaffolded" model, controller, view, ... files, so in those files I have the common code generated by Ruby on Rails generators; in my spec file I have:
it "assigns #article" do
new_article = FactoryGirl.build(:article)
Article.should_receive(:new).and_return(new_article)
post :create
assigns[:article].should eq(new_article)
end
Maybe, (note: the above code is almost the same as that I use to test the new controller action) a better way to test create controller actions would be to pass some attribute value during the post :create action instead of proceed as I make above, but I don't know how to make that and if it is the "right"/"proper" way to make things.
So, what is the proper way to test 'create' controller actions?

I'm doing it this way:
describe "#create" do
before { post :create, { "my_model"=> { "name"=>"name" } } }
specify("should created one my_model") { change{ MyModel.count }.from(0).to(1) }
end
Aaron Sumner who recently wrote the book Everyday Rails Testing with RSpec have an article at his blog. Where he describes it like this:
describe "POST create" do
context "with valid attributes" do
it "creates a new contact" do
expect{
post :create, contact: Factory.attributes_for(:contact)
}.to change(Contact,:count).by(1)
end
it "redirects to the new contact" do
post :create, contact: Factory.attributes_for(:contact)
response.should redirect_to Contact.last
end
end
context "with invalid attributes" do
it "does not save the new contact" do
expect{
post :create, contact: Factory.attributes_for(:invalid_contact)
}.to_not change(Contact,:count)
end
it "re-renders the new method" do
post :create, contact: Factory.attributes_for(:invalid_contact)
response.should render_template :new
end
end
end

How about:
it "creates article" do
article_params = FactoryGirl.attributes_for(:article)
expect { post :create, :article => article_params }.to change(Article, :count).by(1)
end

Related

Testing with Rspec3 controllers with belongs_to association using instance_double

I'm new in testing and learning Rspec, and I can't git it working.
(I have read the book Effective testing with Rspec3, and many tutorials ...also pluralsight.com)
The situation is very simple. In a Companies controller I want to test de Create method, the company model belongs_to user, and is this the code:
I think the problem is when execute
in test: expect(Company).to receive(:new).with(company_params)
or in controller: #company.user=helpers.user
Controller:
class CompaniesController < SessionsController
def create
#company=Company.new(company_params)
#company.user=helpers.user
if #company.save()
redirect_to companies_path
else
render :edit
end
end
and Rspec:
RSpec.describe CompaniesController, type: :controller do
let(:user) { instance_double(User) }
before do
allow_any_instance_of(ApplicationHelper).to receive(:user){user}
allow(controller).to receive(:authorize){true}
end
describe 'Authenticated user with companies' do
let(:company_params) { {company:{name:"Albert",domain:"www.albert.com"}} }
let(:company) { instance_double(Company) }
before do
allow(Company).to receive(:new){company}
end
describe 'POST #create' do
context "with valid data" do
before { allow(company).to receive(:save){true} }
it "redirects to companies_path" do
expect(Company).to receive(:new).with(company_params)
expect(company).to receive(:user=).with(user)
post :create, params:{company: company_params}
expect(response).to redirect_to(companies_path)
end
My intention is very simple: Use instance_double to mock (or stub) #company, and Company.new, using instance double...to test the create action, and simulate the "save()" returning true...etc
I do not know if I explain myself very well, but given the create action of controlloer , how to test using mocks ans stubs, instance_double?
Thanks
First of all let me explain what we need to test here
def create
#company=Company.new(company_params)
#company.user=helpers.user
if #company.save()
redirect_to companies_path
else
render :edit
end
end
We are testing create action of a controller. First let us see what this action does? It's just takes comapany_params as input and create a company record in database.
Testing also goes like the same, we need to just pass the input that action required, and need to check whether it's creating record in database or not.
RSpec.describe CompaniesController, type: :controller do
let(:user) { instance_double(User) }
before do
# all your authentication stubing goes here
allow_any_instance_of(ApplicationHelper).to receive(:user){user}
allow(controller).to receive(:authorize){true}
end
describe 'POST#create' do
context 'with valid attributes' do
before do
post :create, { company:{ name:"Albert", domain:"www.albert.com"} }
end
it 'responds with success' do
expect(response.status).to eq(302)
end
it 'creates company' do
company = Company.find_by(name: "Albert")
expect(assigns(:company)).to eq(company)
expect(response).to redirect_to(companies_path())
end
end
context 'with invalid attributes' do
before do
post :create, { company:{ name:"", domain:""} }
end
it 'renders new template' do
expect(response).to render_template(:edit)
end
end
end
end
No need to sub anything here. As per my knowledge, Only when we use any lib classes / background jobs / third party libraries code inside action then we need to stub those code. Because for all those, we will write specs separately. So no need to test again here that's why we'll do stubing.
Thanks to Narsimha Reddy, I have better ideas about how to test.
Eventhough, if I want to stub
#company=Company.new(company_params)
#company.user=helpers.user
if #company.save()
For testing only de create's response , the solution was in a good use of parameters, and allowing allow(company).to receive(:user=) for the belongs_to association
let(:company_params) {{company:{name:"Albert",domain:"www.albert.com"}}}
let(:ac_company_params) {ActionController::Parameters.new(company_params).require(:company).permit!}
let(:company) { instance_double(Company) }
before do
allow(Company).to receive(:new){company}
allow(company).to receive(:user=)
allow(company).to receive(:save){true}
end
it "redirects to companies_path" do
expect(Company).to receive(:new).with(ac_company_params)
expect(company).to receive(:user=).with(user)
post :create, params: company_params
expect(response).to redirect_to(companies_path)
end

Why are my tests telling me "param is missing or the value is empty:"?

Using Rails 4.2, rspec 2.14, rspec-rails 2.14, faker and factory-girls-rails gems
I have a model called Appointment that I'm running some tests on and everything passes except for the #create under the controller spec.
The error message I get is:
Failure/Error: post :create, FactoryGirl.attributes_for(:appointment)
ActionController::ParameterMissing:
param is missing or the value is empty: appointment
The Appointment model validates the presence of an association to an object called Service.
Here is my factory for appointment.rb:
require 'faker'
FactoryGirl.define do
factory :appointment do |f|
f.service {FactoryGirl.create(:service)}
f.appointment_time { Faker::Time.between(DateTime.now - 1, DateTime.now) }
end
end
Here is my appointment_spec.rb:
require 'spec_helper'
describe Appointment do
it "has a valid factory" do
FactoryGirl.create(:appointment).should be_valid
end
it "is invalid if it does not have a Service association" do
FactoryGirl.build(
:appointment, service: nil).should_not be_valid
end
end
I've been following the instructions listed here for making my Controller Spec. I've also found a lot of stackoverflow posts that say to do the same thing, yet I still get the same error.
Here are the tests not passing from my appointment_controller_spec.rb
describe AppointmentsController do
#other controller action code...
describe "POST #create" do
context "with valid attributes" do
it "saves the new appointment in the database" do
expect {
post :create, FactoryGirl.attributes_for(:appointment)
}.to change(Appointment, :count).by(1)
end
it "redirects to show page" do
post :create, FactoryGirl.attributes_for(:appointment)
response.should redirect_to Appointment.last
end
end
end
I'm at a loss and hoping some one can offer some insight.
EDIT:
As some of you had recommended, I changed the controller spec. This is actually what I had before I changed my code to what you see above:
it "saves the new appointment in the database" do
expect {
post :create, appointment: FactoryGirl.attributes_for(:appointment)
}.to change(Appointment, :count).by(1)
end
The reason I changed this is because when I had this my original error message was:
Failure/Error: expect {
count should have been changed by 1, but was changed by 0
Sorry for the confusion.
I believe you just need your AppointmentsController spec to read as follows:
describe AppointmentsController do
#other controller action code...
describe "POST #create" do
context "with valid attributes" do
it "saves the new appointment in the database" do
expect {
post :create, appointment: FactoryGirl.attributes_for(:appointment)
}.to change(Appointment, :count).by(1)
end
it "redirects to show page" do
post :create, appointment: FactoryGirl.attributes_for(:appointment)
response.should redirect_to Appointment.last
end
end
end
Adding appointment: before you supply the attributes via FactoryGirl in the post call.
Are you using strong_params in your controller? It looks like you are looking for an appointment param, but you are just getting a hash of the attributes.
Try this:
it "saves the new appointment in the database" do
expect {
post :create, appointment: FactoryGirl.attributes_for(:appointment)
}.to change(Appointment, :count).by(1)
end

Rspec having difficulty testing #create with build controller method

So if your #create controller method is simply:
#testimonial = Testimonial.new(testimonial_params)
And you test it in your specs like so:
testimonials_controller_spec.rb
describe "POST #create" do
context "with VALID attributes" do
it "creates new testimonial" do
expect {
post :create, testimonial: FactoryGirl.attributes_for(:testimonial)
}.to change(Testimonial, :count).by(1)
end
end
end
It works fine. The code:
post :create, testimonial: FactoryGirl.attributes_for(:testimonial)
is correct.
However, in my TestimonialsController, my create method is actually:
#testimonial = current_user.testimonials.build(testimonial_params)
My rspec method doesn't work with this. What should I use instead of:
post :create, testimonial: FactoryGirl.attributes_for(:testimonial)
?
Sign in the user before calling the controller action. Please find the following:
#testimonials_controller_spec.rb
require 'rails_helper'
describe TestimonialsController, type: :controller do
let(:user) do
FactoryGirl.create :user
end
before do
sign_in user
end
describe "POST #create" do
context "with VALID attributes" do
it "creates new testimonial" do
expect {
post :create, testimonial: FactoryGirl.attributes_for(:testimonial)
}.to change(Testimonial, :count).by(1)
end
end
end
end
Build doesn't save/persist the record to the database. Why not make it:
#testimonial = current_user.testimonials.new(testimonial_params)
#testimonial.save

rspec controller testing, Expected response to be a <redirect>, but was <200>

I'm using rspec and Factory Girl for testing. When testing the POST #create section of my posts_controller I'm getting the error in the title.
Failures:
1) PostsController POST #create with valid attributes redirects to the post
Failure/Error: response.should redirect_to Post.last
Expected response to be a <redirect>, but was <200>
# ./spec/controllers/posts_controller_spec.rb:59:in `block (4 levels) in <top (required)>'
This is the code from the spec being tested. I'm sure it's not the most efficient way of doing this, but it does work.
def create
#post = Post.new(
:text => post_params[:text],
:embed => post_params[:embed],
:user => current_user,
:title => post_params[:title],
:tag_list => post_params[:tag_list],
:cagegory_ids => post_params[:category_ids]
)
if #post.save
redirect_to #post
else
render 'new'
end
end
...
private
def post_params
params.require(:post).permit(:title, :text, :embed, :user_id, :tag_list,
:category_ids => [])
end
Here's the factory.
FactoryGirl.define do
factory :post do
title { Faker::Lorem.characters(char_count = 20) }
text { Faker::Lorem.characters(char_count = 150) }
user
categories {
Array(5..10).sample.times.map do
FactoryGirl.create(:category)
end
}
end
end
And the relevant part of the spec
describe "POST #create" do
context "with valid attributes" do
it "saves the new post" do
expect{
post :create, post: FactoryGirl.create(:post).attributes
}.to change(Post,:count).by(1)
end
it "redirects to the post" do
post :create, post: FactoryGirl.create(:post).attributes
response.should redirect_to Post.last
end
end
end
The other test, "saves the new post," works fine. I've tried other variations of the redirect_to line, such as "redirect_to(posts_path(assigns[:post])) and it throws the same error.
Any ideas?
OK, I fixed my problem. It isn't pretty but it works.
The issue is with Factory Girl and associations, and I'm definitely not the first to have that problem, but none of the other solutions worked.
I ended up adding this before :each at the top of the POST #create section...
describe "POST #create" do
before :each do
Post.destroy_all
#cat = FactoryGirl.create(:category)
#newpost = FactoryGirl.build(:post)
#post_params = {category_ids: [#cat.id]}.merge(#newpost.attributes)
end
...
...to put the post params into a new hash that I could call later on in the code like this...
it "saves the new post" do
expect{
post :create, post: #post_params
}.to change(Post,:count).by(1)
end
it "redirects to the post" do
post :create, post: #post_params
response.should redirect_to Post.last
end
So this is solved. It adds a bit of overhead to the test but it works. I won't mark this as THE solution for a couple of days in case someone else comes around with some better, simpler code. I definitely welcome any more ideas.
I assume the problem is in factory. Most likely post instance didn't pass validations and controller renders new view, which is not redirect, but success 200. Add logger in the controller and take a look if record actually saves. You can also read through test log tail -f log/test.log.

RSpec Controller Test not generating right url

I am attempting to create a RSpec controller test for a namespaced controller, but rspec doesn't seem able to detect the nesting and generate the proper path for the post :create action.
This is my spec code:
# for: /app/controllers/admin/crm/report_adjustments_controller.rb
require 'spec_helper'
describe Admin::Crm::ReportAdjustmentsController do
render_views
before(:each) do
signin
end
describe "GET 'index'" do
it "returns http success" do
get :index
response.should be_success
end
end
describe "POST 'create'" do
it "creates with right parameters" do
expect {
post :create, report_adjustment: {distributor_id: #ole_distributor.id, amount: "30.0", date: Date.today }
}.to change(Crm::ReportAdjustment, :count).by(1)
response.should be_success
end
end
end
# routes.rb
namespace :admin do
namespace :crm do
resources :report_adjustments
end
end
For this code, the get :index works just fine, but when post :create is called, the following error is generated: undefined method 'crm_report_adjustment_url'
Why would RSpec be smart enough to figure things out with get :index, but not with post :create? How do I get RSpec to properly load the right route, which is admin_crm_report_adjustments_url?
Thanks in advance.
Try posting to the url instead:
post admin_crm_report_adjustments_url
# or
post "/admin/crm/report_adjustments"

Resources