Skip to content

Update scaffold generator to care about --api flag. #1685

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 22, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 7 additions & 68 deletions lib/generators/rspec/scaffold/scaffold_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class ScaffoldGenerator < Base
class_option :orm, :desc => "ORM used to generate the controller"
class_option :template_engine, :desc => "Template engine to generate view files"
class_option :singleton, :type => :boolean, :desc => "Supply to create a singleton controller"
class_option :api, :type => :boolean, :desc => "Skip specs unnecessary for API-only apps"

class_option :controller_specs, :type => :boolean, :default => true, :desc => "Generate controller specs"
class_option :view_specs, :type => :boolean, :default => true, :desc => "Generate view specs"
Expand All @@ -26,10 +27,15 @@ def generate_controller_spec
controller_class_path,
"#{controller_file_name}_controller_spec.rb"
)
template 'controller_spec.rb', template_file
if options[:api]
template 'api_controller_spec.rb', template_file
else
template 'controller_spec.rb', template_file
end
end

def generate_view_specs
return if options[:api]
return unless options[:view_specs] && options[:template_engine]

copy_view :edit
Expand Down Expand Up @@ -58,14 +64,6 @@ def copy_view(view)
File.join("spec/views", controller_file_path, "#{view}.html.#{options[:template_engine]}_spec.rb")
end

def formatted_hash(hash)
formatted = hash.inspect
formatted.gsub!("{", "{ ")
formatted.gsub!("}", " }")
formatted.gsub!("=>", " => ")
formatted
end

# support for namespaced-resources
def ns_file_name
ns_parts.empty? ? file_name : "#{ns_parts[0].underscore}_#{ns_parts[1].singularize.underscore}"
Expand All @@ -83,65 +81,6 @@ def ns_parts
end
end

# Returns the name of the mock. For example, if the file name is user,
# it returns mock_user.
#
# If a hash is given, it uses the hash key as the ORM method and the
# value as response. So, for ActiveRecord and file name "User":
#
# mock_file_name(:save => true)
# #=> mock_user(:save => true)
#
# If another ORM is being used and another method instead of save is
# called, it will be the one used.
#
def mock_file_name(hash = nil)
if hash
method, and_return = hash.to_a.first
method = orm_instance.send(method).split('.').last.gsub(/\(.*?\)/, '')
"mock_#{ns_file_name}(:#{method} => #{and_return})"
else
"mock_#{ns_file_name}"
end
end

# Receives the ORM chain and convert to expects. For ActiveRecord:
#
# should! orm_class.find(User, "37")
# #=> User.should_receive(:find).with(37)
#
# For Datamapper:
#
# should! orm_class.find(User, "37")
# #=> User.should_receive(:get).with(37)
#
def should_receive(chain)
stub_or_should_chain(:should_receive, chain)
end

# Receives the ORM chain and convert to stub. For ActiveRecord:
#
# stub orm_class.find(User, "37")
# #=> User.stub(:find).with(37)
#
# For Datamapper:
#
# stub orm_class.find(User, "37")
# #=> User.stub(:get).with(37)
#
def stub(chain)
stub_or_should_chain(:stub, chain)
end

def stub_or_should_chain(mode, chain)
receiver, method = chain.split(".")
method.gsub!(/\((.*?)\)/, '')

response = "#{receiver}.#{mode}(:#{method})"
response << ".with(#{$1})" unless $1.blank?
response
end

def value_for(attribute)
raw_value_for(attribute).inspect
end
Expand Down
165 changes: 165 additions & 0 deletions lib/generators/rspec/scaffold/templates/api_controller_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
require 'rails_helper'

# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
#
# Also compared to earlier versions of this generator, there are no longer any
# expectations of assigns and templates rendered. These features have been
# removed from Rails core in Rails 5, but can be added back in via the
# `rails-controller-testing` gem.

<% module_namespacing do -%>
RSpec.describe <%= controller_class_name %>Controller, <%= type_metatag(:controller) %> do

# This should return the minimal set of attributes required to create a valid
# <%= class_name %>. As you add validations to <%= class_name %>, be sure to
# adjust the attributes here as well.
let(:valid_attributes) {
skip("Add a hash of attributes valid for your model")
}

let(:invalid_attributes) {
skip("Add a hash of attributes invalid for your model")
}

# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# <%= controller_class_name %>Controller. Be sure to keep this updated too.
let(:valid_session) { {} }

<% unless options[:singleton] -%>
describe "GET #index" do
it "returns a success response" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
<% if RUBY_VERSION < '1.9.3' -%>
get :index, {}, valid_session
<% else -%>
get :index, params: {}, session: valid_session
<% end -%>
expect(response).to be_success
end
end

<% end -%>
describe "GET #show" do
it "returns a success response" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
<% if RUBY_VERSION < '1.9.3' -%>
get :show, {:id => <%= file_name %>.to_param}, valid_session
<% else -%>
get :show, params: {id: <%= file_name %>.to_param}, session: valid_session
<% end -%>
expect(response).to be_success
end
end

describe "POST #create" do
context "with valid params" do
it "creates a new <%= class_name %>" do
expect {
<% if RUBY_VERSION < '1.9.3' -%>
post :create, {:<%= ns_file_name %> => valid_attributes}, valid_session
<% else -%>
post :create, params: {<%= ns_file_name %>: valid_attributes}, session: valid_session
<% end -%>
}.to change(<%= class_name %>, :count).by(1)
end

it "renders a JSON response with the new <%= ns_file_name %>" do
<% if RUBY_VERSION < '1.9.3' -%>
post :create, {:<%= ns_file_name %> => valid_attributes}, valid_session
<% else %>
post :create, params: {<%= ns_file_name %>: valid_attributes}, session: valid_session
<% end -%>
expect(response).to have_http_status(:created)
expect(response.content_type).to eq('application/json')
expect(response.location).to eq(<%= ns_file_name %>_url(<%= class_name %>.last))
end
end

context "with invalid params" do
it "renders a JSON response with errors for the new <%= ns_file_name %>" do
<% if RUBY_VERSION < '1.9.3' -%>
post :create, {:<%= ns_file_name %> => invalid_attributes}, valid_session
<% else %>
post :create, params: {<%= ns_file_name %>: invalid_attributes}, session: valid_session
<% end -%>
expect(response).to have_http_status(:unprocessable_entity)
expect(response.content_type).to eq('application/json')
end
end
end

describe "PUT #update" do
context "with valid params" do
let(:new_attributes) {
skip("Add a hash of attributes valid for your model")
}

it "updates the requested <%= ns_file_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
<% if RUBY_VERSION < '1.9.3' -%>
put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => new_attributes}, valid_session
<% else -%>
put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: new_attributes}, session: valid_session
<% end -%>
<%= file_name %>.reload
skip("Add assertions for updated state")
end

it "renders a JSON response with the <%= ns_file_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
<% if RUBY_VERSION < '1.9.3' -%>
put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => valid_attributes}, valid_session
<% else %>
put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: valid_attributes}, session: valid_session
<% end -%>
expect(response).to have_http_status(:ok)
expect(response.content_type).to eq('application/json')
end
end

context "with invalid params" do
it "renders a JSON response with errors for the <%= ns_file_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@k3rni

you missed moving this file name assignment up to outside of the 1.9.3 conditional, so this does not work on ruby interpreters greater than or equal to 1.9.3, can you add a spec for this case and make it pass? Thanks

<% if RUBY_VERSION < '1.9.3' -%>
put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => invalid_attributes}, valid_session
<% else %>
put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: invalid_attributes}, session: valid_session
<% end -%>
expect(response).to have_http_status(:unprocessable_entity)
expect(response.content_type).to eq('application/json')
end
end
end

describe "DELETE #destroy" do
it "destroys the requested <%= ns_file_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
expect {
<% if RUBY_VERSION < '1.9.3' -%>
delete :destroy, {:id => <%= file_name %>.to_param}, valid_session
<% else -%>
delete :destroy, params: {id: <%= file_name %>.to_param}, session: valid_session
<% end -%>
}.to change(<%= class_name %>, :count).by(-1)
end
end

end
<% end -%>
4 changes: 4 additions & 0 deletions lib/generators/rspec/scaffold/templates/routing_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,21 @@
end

<% end -%>
<% unless options[:api] -%>
it "routes to #new" do
expect(:get => "/<%= ns_table_name %>/new").to route_to("<%= ns_table_name %>#new")
end
<% end -%>

it "routes to #show" do
expect(:get => "/<%= ns_table_name %>/1").to route_to("<%= ns_table_name %>#show", :id => "1")
end

<% unless options[:api] -%>
it "routes to #edit" do
expect(:get => "/<%= ns_table_name %>/1/edit").to route_to("<%= ns_table_name %>#edit", :id => "1")
end
<% end -%>

it "routes to #create" do
expect(:post => "/<%= ns_table_name %>").to route_to("<%= ns_table_name %>#create")
Expand Down
64 changes: 64 additions & 0 deletions spec/generators/rspec/scaffold/scaffold_generator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,44 @@
before { run_generator %w(posts) }
it { is_expected.to contain(/require 'rails_helper'/) }
it { is_expected.to contain(/^RSpec.describe PostsController, #{type_metatag(:controller)}/) }
it { is_expected.to contain(/GET #new/) }
it { is_expected.to contain(/"redirects to the created \w+"/) }
it { is_expected.to contain(/display the 'new' template/) }
it { is_expected.not_to contain(/"renders a JSON response with the new \w+"/) }
it { is_expected.not_to contain(/"renders a JSON response with errors for the new \w+"/) }

it { is_expected.to contain(/GET #edit/) }
it { is_expected.to contain(/"redirects to the \w+"/) }
it { is_expected.to contain(/display the 'edit' template/) }
it { is_expected.not_to contain(/"renders a JSON response with the \w+"/) }
it { is_expected.not_to contain(/"renders a JSON response with errors for the \w+"/) }

it { is_expected.to contain(/"redirects to the \w+ list"/) }
end

describe 'with --no-controller_specs' do
before { run_generator %w(posts --no-controller_specs) }
it { is_expected.not_to exist }
end

describe 'with --api' do
before { run_generator %w(posts --api) }
it { is_expected.to contain(/require 'rails_helper'/) }
it { is_expected.to contain(/^RSpec.describe PostsController, #{type_metatag(:controller)}/) }
it { is_expected.not_to contain(/GET #new/) }
it { is_expected.not_to contain(/"redirects to the created \w+"/) }
it { is_expected.not_to contain(/display the 'new' template/) }
it { is_expected.to contain(/"renders a JSON response with the new \w+"/) }
it { is_expected.to contain(/"renders a JSON response with errors for the new \w+"/) }
it { is_expected.not_to contain(/GET #edit/) }
it { is_expected.not_to contain(/"redirects to the \w+"/) }
it { is_expected.not_to contain(/display the 'edit' template/) }
it { is_expected.to contain(/"renders a JSON response with the \w+"/) }
it { is_expected.to contain(/"renders a JSON response with errors for the \w+"/) }

it { is_expected.not_to contain(/"redirects to the \w+ list"/) }

end
end

describe 'namespaced controller spec' do
Expand Down Expand Up @@ -119,6 +151,30 @@
end
end

describe 'with --api' do
before { run_generator %w(posts --api) }

describe 'edit' do
subject { file("spec/views/posts/edit.html.erb_spec.rb") }
it { is_expected.not_to exist }
end

describe 'index' do
subject { file("spec/views/posts/index.html.erb_spec.rb") }
it { is_expected.not_to exist }
end

describe 'new' do
subject { file("spec/views/posts/index.html.erb_spec.rb") }
it { is_expected.not_to exist }
end

describe 'show' do
subject { file("spec/views/posts/index.html.erb_spec.rb") }
it { is_expected.not_to exist }
end
end

describe 'with --no-view-specs' do
before { run_generator %w(posts --no-view-specs) }

Expand Down Expand Up @@ -152,11 +208,19 @@
it { is_expected.to contain(/require "rails_helper"/) }
it { is_expected.to contain(/^RSpec.describe PostsController, #{type_metatag(:routing)}/) }
it { is_expected.to contain(/describe "routing"/) }
it { is_expected.to contain(/routes to #new/) }
it { is_expected.to contain(/routes to #edit/) }
end

describe 'with --no-routing-specs' do
before { run_generator %w(posts --no-routing_specs) }
it { is_expected.not_to exist }
end

describe 'with --api' do
before { run_generator %w(posts --api) }
it { is_expected.not_to contain(/routes to #new/) }
it { is_expected.not_to contain(/routes to #edit/) }
end
end
end