rspec controller test can't find partial - ruby-on-rails

I'm using render_to_string as a json response. It works fine in my app, but rspec can't find the partial.
controller:
# controllers/admin_controller.rb
class AdminController < ApplicationController
def retrieve_edit_form
user = User.find(params[:id])
form = render_to_string('_user_form', layout: false)
respond_to do |format|
format.json { render json: { form: form } }
end
end
end
spec:
# spec/app/controllers/admin_controller_spec.rb
require 'rails_helper'
RSpec.describe AdminController, type: :controller do
render_views
describe 'GET retrieve_edit_form' do
it 'returns http success' do
get :retrieve_edit_form, id: 100, format: :json
expect(response).to be_success
end
end
end
I get the error:
Missing template admin/_user_form, application/_user_form with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee]}. Searched in:
* "/Users/.../app/views"
How can I get rspec to recognize the partial?

Ok, I figured it out. Turns out I needed to add the extension to the partial and it all works fine.
The controller needed to be
form = render_to_string('_user_form.html.erb', layout: false)

Related

ActionView::MissingTemplate, Rails 5 API with JSON

I am consistently getting an ActionView::MissingTemplate error when trying to render JSON in my Rails 5 Api. I just want to render the pure JSON, without a jbuilder or other view. Can anyone help?
thing_controller.rb:
class Api::ThingController < ApplicationController
def thing
render json: {error: 'This is my error message.'}, status: 422
end
end
thing_controller_test.rb:
require 'test_helper'
class Api::ThingControllerTest < ActionDispatch::IntegrationTest
test "the truth" do
get '/api/thing'
assert_response 422
end
end
full error message:
Error: Api::ThingControllerTest#test_the_truth:
ActionView::MissingTemplate: Missing template api/thing/thing,
application/thing with {:locale=>[:en], :formats=>[:json],
:variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby,
:jbuilder]}.
application_controller.rb:
class ApplicationController < ActionController::API
include ActionController::Caching
include ActionController::ImplicitRender # want implicit view rendering for JBuilder
before_action :add_cors_headers
def options
head(:ok) if request.request_method == "OPTIONS"
end
This is related to an issue in Rails 5 beta ActionController::API and Jbuilder. It looks like it has been fixed by this pull request.
Meantime you can return plain text and set the content type, like so:
render plain: {error: 'This is my error message.'}.to_json, status: 422, content_type: 'application/json'

Rails json API with Rspec -> ActionView::MissingTemplate

So I have an api under
#controllers/api/v4/...rb
this api render jbuilder json under:
#views/api/v4/....json.jbuilder
I have spec:
#spec/controllers/api/v4/..._spec.rb
require 'rails_helper'
RSpec.describe Api::V4::AlbumsController do
let(:user) { create(:user) }
before(:each) do
#request.env["devise.mapping"] = Devise.mappings[:user]
sign_in(user)
end
describe "GET index" do
it "returns correct types" do
get :index, {:format => :json, :user_id => user.id}
puts #request.body
puts response.body
user_response = json_response
puts user_response
end
end
end
Everything is right until rendering when I get this:
Failure/Error: get :index, {:format => :json, :user_id => user.id}
ActionView::MissingTemplate:
Missing template api/v4/albums/index, api/api/index with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :coffee, :haml]}. Searched in:
* "#<RSpec::Rails::ViewRendering::EmptyTemplatePathSetDecorator:0x007ff4721d9f20>"
Does someone have an idea to solve this?
I needed to include jbuilder in my gemfile... so it can render the .json.jbuilder views.

rails 4 template missing error in render in ajax

I have the following ajax function
$.ajax({
url: '/sub_categories/sub_cat',
data: 'sub_cat=45',
success: function() {
alert('success');
}
})
Here is my controller
require 'json'
class SubCategoriesController < ApplicationController
def show
end
def sub_cat
#sub_categories = SubCategory.where(category_id: params[:cat_id])
html = render_to_string 'sub_categories/sub_cat'
response_html true,html
end
end
My application controller
def response_html status,html
respond_to do |format|
format.json {render json: {
status: status,
html: html,
}
}
format.html
end
end
I have json file in sub_categories/sub_cat.json.erb
When I run getting error as
ActionView::MissingTemplate at /sub_categories/sub_cat.json
Missing template sub_categories/show, application/show with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in:
* "/home/editmehere/Documents/site/name/app/views"
My route.rb has
resources :sub_categories do
get 'sub_cat', on: :collection
end
Why I am getting error like this and how can I solve it. Can anyone help me to solve it.
I'm guessing you're trying to keep your application dry, but why don't you just use this in your SubCategoriesController:
class SubCategoriesController < ApplicationController
def sub_cat
#sub_categories = SubCategory.where(category_id: params[:cat_id])
respond_to do |format|
format.json
format.html
end
end
end
This will allow you to call sub_cat.json.erb without having to pass the status var, or pre-render the HTML. This is just convention, so apologies if it's not what you need. I see a lot of people on here overcomplicate things, when simplicity would work much better
Ajax
Also, I believe you've got a problem with your ajax data var:
data: 'sub_cat=45',
should be
data: {sub_cat: "45"},

test missing template

Trying to write what should be a straightforward RSpec test and have set up my create action to render JSON like the following:
require 'spec_helper'
describe CommentsController do
let(:valid_attributes) do
{
title: 'First Comment', comment_text: 'LoremIpsum', commentable_id: 1,
user_id: 1, entered_by: 'john', last_updated_by: 'doe'
}
end
context 'JSON' do
describe 'POST create' do
describe 'with valid params' do
it 'creates a new Comment' do
json = {:format => 'json', :comment => valid_attributes}
post :create, json
end
it 'assigns a newly created comment as #comment' do
json = {:format => 'json', :comment => valid_attributes}
post :create, json
assigns(:comment).should be_a(Comment)
assigns(:comment).should be_persisted
end
end
end
end
end
However I am getting the following output:
ActionView::MissingTemplate: Missing template comments/create, application/create with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee, :haml]}. Searched in:
you missed the else part when #commentable is nil. this will try rendering the default template!
to clarify:
this is what was posted initially:
def create
if #commentable
#comment = #commentable.comments.new(comment_params)
if #comment.save
render json: #comment, status: :created
else
render json: #comment.errors, status: :unprocessable_entity
end
end
end
in the case where #commentable is nil there is nothing that tells rails what to render, so it will try to render the default template for the create action. this is where Missing template comments/create comes from.
what i mean with the else part is this:
def create
if #commentable
[...]
else
head 404
end
end

action mailer gives error while passing layout

in my action mailer(rails 3.2.13) I have something like
class RepaymentMailer < ActionMailer::Base
default from: "repayments#milaap.org"
def repayment_mail user, user_repayment_info, month_date
#mail_layout = if condition_true
'layout1'
else
'layout2'
end
mail(to: "#{user.first_name} <#{user.email}>",
from: "xxx#xxx.org",
bcc: ["xxx <xxx#xxx.org>"],
reply_to: 'xxx#xxx.org',
subject: "this is a test" ) do |format|
format.html { render layout: #mail_layout }
format.text
end
end
end
when I do
puts RepaymentMailer.repayment_mail(param1, param2, param3).deliver
it gives me error that even if repayment_mail template exist
ActionView::MissingTemplate: Missing template repayment_mailer/repayment_mail with {:locale=>[:en], :formats=>[:text], :handlers=>[:erb, :builder, :coffee, :arb]}. Searched in:
If I remove
do |format|
format.html { render layout: #mail_layout }
format.text
end
then It works without error.
But Obviously I want the desired layout. What can be the cause of the error.
Because in your error, it is clearly showing that problem is with this line:
Missing template repayment_mailer/repayment_mail with {:locale=>[:en], :formats=>[:text]**, :handlers=>[:erb, :builder, :coffee, :arb]}.
I think you didn't read the lines below:
class UserMailer < ActionMailer::Base
def welcome_email(user)
mail(to: user.email) do |format|
format.html { render layout: 'my_layout' }
format.text
end
end
end
This will render the HTML part using the my_layout.html.erb file and the text part with the usual user_mailer.text.erb file if it exists.
Please read here.
Thanks

Resources