Week 2 Questions Flashcards
How would you generate a mailer and it’s email templates?
rails generate mailer UserMailer account_activation password_reset
When you generate a mailer in the command line it creates two views for the email template. Why does this happend
One for plain-text email and one for HTML email.
What does user:references add in this migration:
rails generate model Micropost content:text user:references
Automatically adds a user_id column (along with an index and a foreign key reference)3 for use in the user/micropost association.
How do you set a default scope for an object to be in descending order
#in the model default_scope -> { order(created_at: :desc) }
What validation would you write to destroy a post that belongs to a user that has been destroyed
#in user model has_many :microposts, dependent: :destroy
How would you code a shared errors partial and how would you code the render snippet?
<div> <div class="alert alert-danger"> The form contains . </div> <ul>
<li> </ul>
</div>
Explain this code:
Micropost.where(“user_id = ?”, id)
Find microposts where the user_id is equal to the id of the current user
How would you use the pluralize method on microposts belonging to a user
What does the request.referrer method do?
It goes to the previous URL
In one line, how would you write an image tag that displays a micropost’s image if it has one
In the ruby language, what are the differences between Array.length, Array.size, and Array.count?
Array#length method used on arrays in ruby returns the number of elements in the array
Array#size is just an alias to the Array#length method. It executes same Array#length method internally.
Array#count has some more functionalities than length/size. It can be used for getting number of elements based on some condition.
3 ways to use Array#count:
c = [1,2,3,4,4,7,7,7,9]
1. Array#count Returns number of elements in Array
c.count
=> 9
2. Array#count n Returns number of elements having value n in Array
c.count 7
=> 3
3. Array#count{|i| i.even?} Returns count based on condition invoked on each element array
c.count {|i| i>5}
=> 4
How would you write an if else statement depending on a specific controller action?
if params[:action] == "foo" # Show stuff for action 'foo' elsif params[:action] == "bar" # Show stuff for action 'bar' elsif ... # etc. end
How do you apply a layout in the controller?
#create a new layout_name.hmtl.erb file under layouts in views #in the controller layout 'layout_name'
How do you view all the rails generator commands in the terminal?
rails g
What is required at the top of each spec?
require ‘rails_helper’
Write a simple feature spec for visiting the homepage and seeing a h1 tag with jar of awesome as the text
require 'rails_helper' feature "user visits homepage" do scenario "successful visit" do visit root_path expect(page).to have_css 'h1', text: 'Jar of Awesome' end end
How would you write an acceptance test for the creation of a note?
require 'rails_helper' feature "User create note" do scenario "successful" do visit root_path click_on "New Note" fill_in "Conent", with: "Ate pad thai with sweet tangerines" click_on "Submit"
expect(page).to have_css '.notes', text: 'Ate pad thai with sweet tangerines' end end
Where do you place Object Pattern
spec/support/object_pattern.rb
How do you include Capybara methods in a Object Pattern file?
include Capybara::DSL in the class
class NewNoteForm
include Capybara::DSL
end
When writing methods for Object Pattern, why would you return self in this method? def visit_page visit('/') click_on "New Note" self end
You return self so that you can chain multiple methods to the object.
What do you have to add to the top of the spec to use and Object Pattern object?
require_relative ‘../support/new_note_form’
How do you code a let statement for a new_note_form
let(:new_note_form){NewNoteForm.new}
How would you write a scenario test using Factory Girl that visits the show page of a particular note object that has content ‘Just did it’?
scenario ‘note page’ do
note = FactoryGirl.create(:note, content: ‘Just did it’)
visit(‘/notes/#{note.id}’)
expect(page).to have_content('Just did it') end
fix this–>How would you write the enum for a privacy option for a note class in the note.rb file? How would you write the input for a privacy option using simple form?
simple form in views
#note.rb enum privacy: [:public_note, :private_note, :friends_access]
Explain this line of code note = FactoryGirl.create(:note, content: ‘Just did it’)
variable name note
is equal to
A Factory Girl create factory called :note
In this situation we are over riding the default factory’s value of the content: attribute with ‘Just did it’
How would you code a sequence in a note factory for the content attribute?
sequence(:content){|n| “Note content #{n}”}
How would you create a sub factory for a note factory with private access?
factory :public_note do
privacy Note.privacy[:public_access]
end
Explain this line of code:
notes = FactoryGirl.create_list(:note, 3)
variable notes
equal
FactoryGirl creates list of 3 note factories
What does controller do?
- authenticate and authorize requests
- handle models
- create response
a) render template
b) respond with required format and headers (e.g. JSON)
c) redirect to another route
RSpec.describe NotesController, type: :controller do
end
What parts of this line of code can can be removed/are optional?
#new code describe NotesController do end
# type: :controller Because our spec is placed in the controller folder, Rails knows that this spec if for a controller and the line of code is not necessary but still works if you want your spec to be extra specific
How do you write the describe description for testing controller actions?
decribe "GET new" do #request type #name of action
What are the 4 things you should write testing for when testing controllers?
authentication
authorization
response
data assignment
what gem must you add to your gemfile to test controllers?
gem ‘rails-controller-testing’
How do you test for a get response of the new page?
it “renders :new template” do
get :new
expect(response).to render_template(:new)
end
Write the rest of this test
it “assigns new Note to @note”
it “assigns new Note to @note” do
get :new
expect(assigns(:note)).to be_a_new(Note)
end
#assigns contains all instance variables of the action #assigns takes a symbol as the instance variable name #be_a_new takes a class and makes sure that the assigned object is a new measure of this provided class
Finish the rest of this test:
let(:note) {FactoryGirl.create(:public_note)}
it “renders :show template” do
end
let(:note) {FactoryGirl.create(:public_note)}
it “renders :show template” do
get :show, id: note.id
expect(response).to render_template(:show)
end
#The class is Note #Include a factory for an inherited factory called :public_note it "redirect_to :show template" do
end
it “redirect_to :show template” do
post :create, note: FactoryGirl.attributes_for(:public_note)
expect(response).to redirect_to(note_path(assigns[:note]))
end
What does this code do?
expect {
post :create, note: FactoryGirl.attributes_for(:public_note)
}.to change(Note, :count).by(1)
it compares the count of Note before and after the code in expect is run after comparing, the count should change by 1
What does the change matcher do?
The change matcher is used to specify that a block of code changes some mutable state.
You can specify what will change using either of two forms:
expect { do_something }.to change(object, :attribute)
expect { do_something }.to change { object.attribute }
You can further qualify the change by chaining from and/or to or one of by, by_at_most,
by_at_least.
In Capybara, what is the difference between:
click_link(‘Link Text’)
click_button(‘Save’)
click_on(‘Link Text’)
click_link(‘Link Text’)# clicks on links
click_button(‘Save’)# clicks on buttons
click_on(‘Link Text’)# clicks on either links or buttons
What is assigns(:note) equivalent to while used as an argument in the expect() method?
it is equivalent to an instance variable
When writing an action for a Page Object Pattern class, what does the params={} in the action fill_in_with do? def fill_in_with(params={})
This action takes attributes that will be passed into the params of the page
How would you provide a defalut value for the following action of a Page Object Pattern class?
def fill_in_with(params = {})
fill_in(‘Title’, with: :title, ‘Read a book’)
fill_in(‘Description’, with: ‘Excellent read’)
select(‘Public’, from: ‘Privacy’)
check(‘Featured achievement’)
attach_file(‘Cover image’, “#{Rails.root}/spec/fixtures/cover_image.png”)
self end
wrap the value in params.fetch(:attribute_symbol, value_to_make_defalut)
example:
fill_in(‘Title’, with: params.fetch(:title, ‘Read a book’params.fetch)
What is the definition of:
fetch(key, *args)
Returns a parameter for the given key. If the key can’t be found, there are several options: With no other arguments, it will raise an ActionController::ParameterMissing error; if more arguments are given, then that will be returned; if a block is given, then that will be run and its result returned.
params = ActionController::Parameters.new(person: { name: ‘Francesco’ })
params. fetch(:person) # => {“name”=>”Francesco”}
params. fetch(:none) # => ActionController::ParameterMissing: param is missing or the value is empty: none
params. fetch(:none, ‘Francesco’) # => “Francesco”
params. fetch(:none) { ‘Francesco’ } # => “Francesco”
When would you use sequences in FactoryGirl
If you want to create multiple objects to be tested and you want to by-pass uniqueness validations set in the model
How do you write the describe description shorthand for a method and an instance method?
describe ‘.authenticate’ do
describe ‘#admin?’ do
What is the difference between Class and Instance Methods
Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. example: class Foo def self.bar puts 'class method' end
def baz
puts ‘instance method’
end
end
Foo.bar # => "class method" Foo.baz # => NoMethodError: undefined method ‘baz’ for Foo:Class
Foo.new.baz # => instance method
Foo.new.bar # => NoMethodError: undefined method ‘bar’ for #
Name 3 ways to create a class method in ruby
# Way 1 class Foo def self.bar puts 'class method' end end
Foo.bar # “class method”
# Way 2 class Foo class << self def bar puts 'class method' end end end
Foo.bar # “class method”
# Way 3 class Foo; end def Foo.bar puts 'class method' end
Foo.bar # “class method”
Name 3 ways to create an instance method in ruby
class Foo def baz puts 'instance method' end end
Foo.new.baz # “instance method”
Way 2
class Foo
attr_accessor :baz
end
foo = Foo.new
foo.baz = ‘instance method’
puts foo.baz
# Way 3 class Foo; end
foo = Foo.new
def foo.bar
puts ‘instance method’
end
Foo.new.baz # “instance method”
How long should a spec description be?
40 characters If longer consider using the context method: BAD it 'has 422 status code if an unexpected params will be added' do GOOD context 'when not valid' do it { is_expected.to respond_with 422 } end
What is lazy loading and explain a benefit of it?
Your database is queried only when data from the database is required for some kind of manipulation in code.
This design pattern decreases the time required by an application to boot by distributing the computation cost during the execution. Also, if a specific feature is never used, the computation won’t be executed at all.