How to render the next view in a controller test - ruby-on-rails

My controller action does the following:
Saves a newly POSTed instance of a user
Sends an email to the new user
Redirects to the user's homepage
I'm doing some quick and dirty view tests, just in the controller test... not robust enough for me to want to separate out into view test.
The problem is that I can test #1 and #2, but not #3. In other words, here is my test code:
describe "create - with valid, new data" do
it "creates a new signup" do
expect{
post :create, signup: FactoryGirl.attributes_for(:signup)
}.to change(Signup,:count).by(1)
end
it "redirect to form page" do
post :create, signup: FactoryGirl.attributes_for(:signup)
response.should render_template "subscribe/notification_email"
end
it "redirect to form page" do
post :create, signup: FactoryGirl.attributes_for(:signup)
response.should render_template "homepage"
end
end
The first two tests are passing, the last is failing. Is there a way to tell the controller test to go to the next thing that is rendered? Or how else can I test this?

Related

undefined local variable or method `params' for controller

I am trying to implement contact manager with rails. I am using RSpec for test-driven development.
"When I am looking at a single person’s page, I click an add link that takes me to the page where I enter the phone number. I click save, then I see the person and their updated information"
I am trying to validate this action.
In my controller class
describe "POST #create" do
context "with valid params" do
let(:alice) { Person.create(first_name: 'Alice', last_name: 'Smith') }
let(:valid_attributes) { {number: '555-1234', person_id: alice.id} }
it "creates a new PhoneNumber" do
expect {
post :create, params: {phone_number: valid_attributes}, session: valid_session
}.to change(PhoneNumber, :count).by(1)
end
it "redirects to the phone number's person" do
post :create, params: {:phone_number => valid_attributes}, session: valid_session
#phone_number = PhoneNumber.new(person_id: params[:person_id])
expect(response).to redirect_to(#phone_number.person)
end
end
I want to redirect to phone number's person but while getting phone number
It gives me an error undefined local variable or method params' for #<RSpec::ExampleGroups::PhoneNumbersController::POSTCreate::WithValidParams:0x00007fc89e276898>
I also have view test as follows
it 'adds a new phone number' do
page.click_link('Add phone number')
page.fill_in('Number', with: '555-8888')
page.click_button('Create Phone number')
expect(current_path).to eq(person_path(person))
expect(page).to have_content('555-8888')
end
Right now this test is also failing because of this error :
expected: "/people/1"
got: "/phone_numbers"
How can I resolve these problems and redirect user as desired? Thanks in advance
There's no such thing as params in your test.
Instead of...
#phone_number = PhoneNumber.new(person_id: params[:person_id])
...you could do...
#phone_number = PhoneNumber.new(person_id: valid_attributes[:person_id])
But since you're just testing that you redirected to the person, you could remove the above line completely and do
expect(response).to redirect_to(alice)

I'm DRYing my specs, but have a issue with making dynamic requests for controller tests

I was noticing that I kept repeating the same spec for actions prohibited to certain users. Especially when the action is not allowed, the redirect and flash should always be the same (more or less), so I tried writing a shared_example like this:
shared_examples_for "no access" do |action|
it "redirects the user to the homepage" do
get action
subject.should redirect_to('/')
end
it "sets a flash message" do
get action
expect(controller).to set_flash[:alert]
end
end
But then quickly realised that get doesn't accept the action variable as a variable.
Any idea on fixing this, or achieving something like this some other way?
Specify your shared example as follows...
shared_examples "no access" do
it "redirects the user to the homepage" do
action
expect(response).to redirect_to('/')
end
end
Then in your tests you pass action as a let block...
it_behaves_like "no access" do
let(:action) {get :show, id: my_record.id}
end

RSpec Routing Spec POST Request Problems

I'm a Ruby on Rails developer and I was testing a fairly simple Rails application using RSpec. I was writing some Routing specs and then I faced this problem:
My routes are like this:
Rails.application.routes.draw do
root 'trip_plans#index'
resources :trip_plans
end
So I have a route like post /trip_plans for creating new plans and triggering the trip_plans#create action.
My Routing spec file spec/routing/trip_plans_spec.rb looks like this:
require 'rails_helper'
RSpec.describe 'trip_plans routes', type: :routing do
describe 'creating a new plan' do
it 'creates a new plan on post in /trip_plans' do
expect(post: '/trip_plans').to route_to(controller: 'trip_plans', action: 'create', title: 'New Plan', day: '3')
end
end
end
Now I need to somehow pass the params title: 'New Plan', day: '3' to my expect(post: '/trip_plans') so it seems like a real user is filling in the forms and hitting submit.
How do I pass params for POST requests to my RSpec Routing spec?
Thanks in advance!
Routing specs don't often add much value. In a routing spec you simply test that a certain route matches the correct controller. The controller is never actually called.
Instead what you can use are controller specs which are used to test how your application responds to user input:
# spec/controllers/trip_plans_controller_spec.rb
RSpec.describe TripPlansController, type: :controller do
let(:valid_params) do
{
title: 'New Plan',
day: '3'
}
end
let(:invalid_params) do
{
day: 'xxx'
}
end
describe 'POST #create' do
let(:action) { post :create, valid_params }
context 'with valid attributes' do
it 'creates a new post' do
expect { action }.to change(Post, :count).by(+1)
end
it 'has the correct attrributes' do
action
expect(assigns(:trip_plan).title).to eq 'New Plan'
expect(assigns(:trip_plan).day).to eq 3
end
end
context 'with invalid attributes' do
let(:action) { post :create, invalid_params }
it 'does not create a new post' do
expect { action }.to_not change(Post, :count)
end
it 'renders the new template' do
action
expect(response).to render_template :new
end
end
end
end
and feature specs which are end to end specs which test the actual user experience:
RSpec.feature 'Trip Plans' do
context 'as a User' do
scenario 'I should be able to create a trip plan' do
visit root_path
click_link 'Create a new trip plan'
fill_in 'Title', with: 'Go west'
fill_in 'Day', with: 5
click_button 'Create trip plan'
expect(page).to have_content 'Trip plan created.'
expect(page).to have_content 'Go west'
end
end
end
Controller specs are very useful for testing exactly how your controller responds to params and where you write actual expectations on the database state.
Feature specs are nice since they cover your views as well and well written specs also guarantee that your user paths are accessible. However they often do not catch errors which are not readily apparent from the front end and are slower, since you often need to render several pages to get to the actual meat of the test.
The stack trace or error message from feature specs is often less useful than lower level specs.
A good test suite is usually made of a combination of model specs, controller specs and feature specs which cover the most important paths through the application.

Optimize Rails RSpec Tests

I'm working on a test for my Rails 4 app and I'm pretty new to using RSpec. I have a controller named AppsController which has the standard index, new, show, create... methods and they all work the way Rails suggest Etc. "new" creates a new instance of the object and create actually saves it, show, shows it and index shows all of the object. Here are my current tests can anyone see any potential problems or things that i could improve?
FactoryGirl.define do
factory :developer do
email 'example#me.com'
password 'new_york'
password_confirmation 'new_york'
tos '1'
end
factory :app do
name 'New App'
tos '1'
end
factory :invalid_app, parent: :app do
name 'nil'
tos '0'
end
end
require 'spec_helper'
def create_valid!
post :create, app: app_attributes
end
def create_invalid!
post :create, app: app_invalid_attributes
end
def show!
get :show, id: app
end
def update_valid!
put :update, id: app, app: app_attributes
end
def update_invalid!
put :update, id: app, app: app_invalid_attributes
end
def delete!
delete :destroy, id: app
end
def http_success
expect(response).to be_success
end
def expect_template(view)
expect(response).to render_template(view)
end
describe AppsController do
render_views
before(:each) do
#developer = FactoryGirl.create(:developer)
#developer.confirm!
sign_in #developer
end
let(:app) { FactoryGirl.create(:app, developer: #developer) }
let(:app_attributes) { FactoryGirl.attributes_for(:app) }
let(:app_invalid_attributes) { FactoryGirl.attributes_for(:invalid_app) }
describe 'GET #index' do
it 'responds with an HTTP 200 status' do
get :index
http_success
end
it 'renders the :index view' do
get :index
expect_template(:index)
end
it 'populates #apps with the current_developers apps' do
app = FactoryGirl.create(:app, :developer => #developer)
get :index
expect(assigns(:app)).to eq([app])
end
end
describe 'POST #create' do
context 'with valid parameters' do
it 'creates a new app' do
expect { create_valid!
}.to change(App, :count).by(1)
end
it 'redirects to the new app keys' do
create_valid!
expect(response).to redirect_to keys_app_path(App.last)
end
end
context 'with invalid parameters' do
it 'does not create the new app' do
expect { create_invalid!
}.to_not change(App, :count)
end
it 'renders the :new view' do
create_invalid!
expect_template(:new)
end
end
end
describe 'GET #show' do
it 'responds with an HTTP 200 status' do
show!
http_success
end
it 'renders the :show view' do
show!
expect_template(:show)
end
it 'populates #app with the requested app' do
show!
expect(assigns(:app)).to eq(app)
end
end
describe 'PUT #update' do
context 'with valid parameters' do
it 'locates the requested app' do
update_valid!
expect(assigns(:app)).to eq(app)
end
it 'changes app attributes' do
update_valid!
expect(app.name).to eq('Updated App')
end
it 'redirects to the updated app' do
update_valid!
expect(response).to redirect_to app
end
end
context 'with invalid parameters' do
it 'locates the requested app' do
update_invalid!
expect(assigns(:app)).to eq(app)
end
it 'does not change app attributes' do
update_invalid!
expect(app.name).to_not eq('Updated App')
end
it 'renders the :edit view' do
update_invalid!
expect_template(:edit)
end
end
end
describe 'DELETE #destroy' do
it 'deletes the app' do
expect { delete!
}.to change(App, :count).by(-1)
end
it 'redirects to apps#index' do
delete!
expect(response).to redirect_to apps_url
end
end
end
count should have been changed by -1, but was changed by 0 - on DELETE #destroy
expecting <"new"> but rendering with <[]> - on POST #create
expected: "Updated App"
got: "New App" - on PUT #update
expecting <"edit"> but rendering with <[]> - on PUT #update
expected: [#<App id: nil, unique_id: "rOIc5p", developer_id: 18, name: "New App">]
got: nil - on GET #index
Small thing - your #http_success method is testing the exact same thing twice.
You could also factor out the references to app by putting a #let statement right after your #before block:
let(:app) { FactoryGirl.create(:app, developer: #developer) }
then in your specs, just
it 'renders the :show view' do
get :show, id: app
expect_template(:show)
end
Edit:
Then the order of operations will be 1) the #developer is created in the #before block, 2) the spec is entered, 3) at the first reference to app in the spec, the #let block will create an instance of an app.
That means you can't factor out the app creation in the #index spec, because in that case the spec will call the action before it creates the app.
A few things I thought of, reading your code:
You don't need to include parens on method calls taking no arguments. Just http_success will work.
You should get try to use the modern RSpec expectation syntax consistently. Instead of assigns(:app).should eq(app), use expect(assigns(:app)).to eq(app). (There's one exception to this, which is expectations on mocks (ie. should_receive(:message)), which will only take on the modern expect-to syntax as of RSpec 3.
For controller specs, I like to create little methods for each action that actually invokes the action. You'll notice you call get :show, id: app several times in the GET #show specs. To DRY up your specs a little more, you could instead write the following method within the describe block:
def show!
get :show, id: app
end
Try to use one Hash syntax consistently. What's more, Rails 4 can't be run with Ruby 1.8, so there's (nearly) no reason to use the hash-rocket Hash syntax.
If I'm getting really, really picky, I usually consider instance variables in a spec to be a smell. In almost all cases, instance variables should be refactored to a memoized let/given blocks.
If I'm getting really, really, really picky, I prefer to think of controller specs such as yours as strictly a unit test of the controller, not an integration test (that's what Capybara is for), and as such you shouldn't be exercising your model layer at all. You should only be testing that your controller is sending the right messages to the model layer. In other words, all the model layer stuff should be stubbed out. For example:
describe 'GET #show' do
let(:app) { stub(:app) }
before do
App.stub(:find).and_return(app)
end
it 'populates #app' do
get :show, id: app
assigns(:app).should eq(app)
end
end
I know this last is a personal preference, not a metaphysical truth or even necessarily a wide-spread standard convention, so you may choose to take it or leave it. I prefer it, because it keeps my specs very speedy, and gives me a very clear heuristic for when my controller actions are doing too much, and I might need to consider refactoring. It could be a good habit to get into.
First, I'm not certain but I suspect your invalid app factory may be wrong. Did you mean
factory :invalid_app, parent: :app do
name nil
tos '0'
end
nil as a ruby NilClass not "nil" as a string?
As for other comments about cleanup and stuff, here are a few of my thoughts.
You can avoid the need for some of your helper methods and duplication by using before blocks for each describe. Taking just your index tests you could have something more like
describe 'GET #index' do
before do
get :index
end
it 'responds with an HTTP 200 status' do
http_success
end
it 'renders the :index view' do
expect_template(:index)
end
it 'populates #apps with the current_developers apps' do
expect(assigns(:app)).to eq([app])
end
end
Notice also that you don't need to recreate app because your let is doing it as necessary.
On the failures, I suspect the delete count change could be failing because inside the expectation, the test framework is creating a new app (from the let) and then deleting it leading to a count change of 0. For that test, you need to make sure you're app is created outside of your expectation. Because you are using let, you could do that like this:
describe 'DELETE #destroy' do
it 'deletes the app' do
# ensure that app is already created
app
expect {
delete!
}.to change(App, :count).by(-1)
end
end
alternatively, change the let to a let! which will force the creation before the specs actually run.
As for other failures, thought #DanielWright suggested the helper methods, I find those complicate the debug. I can't see where you set the app name to "Updated App", for example. Perhaps a clearer test (for that particular one) would not use the helper methods but could be more explicit. Something like
describe 'PUT #update' do
let(:app_attributes) { FactoryGirl.attributes_for(:app, name: 'The New App Name') }
before do
put :update, id: app, app: app_attributes
end
context 'with valid parameters' do
it 'locates the requested app' do
expect(assigns(:app)).to eq(app)
end
it 'changes app attributes' do
# notice the reload which will make sure you refetch this from the db
expect(app.reload.name).to eq('The New App Name')
end
it 'redirects to the updated app' do
expect(response).to redirect_to app
end
end
end
For the other errors, you might want to start debugging your code. Are you certain it should work? Have you looked at output logs? Maybe the tests are doing there job and finding errors in your controller code. Have you done any step-through debugging?

What is the proper way to test 'create' controller actions?

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

Resources