Skip to content

Devise Knowledge Map

Joana Be edited this page Dec 5, 2019 · 4 revisions

Guide

http://devise.plataformatec.com.br/

Role Dependent Action

To get the currently logged in user, use current_user inside a controller. On current_user you can access all attributes of a user like defined in the db schema. E.g. using

def new
    if !current_user.is_student?
      @lecture = Lecture.new
    end
end

would make the new operation of lectures only available to any user that is not a student.

Testing

To test the example code mentioned in the section above, you must make sure to first log in. This can be done by e.g.

def login_student
    user = FactoryBot.create(:user, :student)
    sign_in(user, scope: :user)
end

And used in the test itself like this:

it "does not redirect for student" do
      login_student
      get :new, params: {}, session: valid_session
      expect(response).to redirect_to(lectures_url)
end

A few examples can be found in `spec\features\user_edit_spec.rb.

However, as seen in lectures_controller_spec.rb, tags can help easily executung login_xy for you. You add tags with

it "a test case which should perform certain actions based on the tag", :logged_student do

and access it in e.g. a before each like

before(:each) do |test|
    if test.metadata[:logged_student]
      login_student
    end
  end

to execute action dependent on the tag.

Display Text With i18n

Devise uses i18n which helps displaying text in several translations. So if you have a button that should display "Update", the correct way of embedding the text is by using t('.update'):

<div class="form-group">
    <%= f.submit t('.update'), class: 'btn btn-primary' %>
</div>

. For '.update' to be found, add a path of the view you are currently in to the corresponding file in config >> locales. So if you added this button to views >> users >> registrations >> edit, change the users.en.yml file to include

en:
  users:
    registrations:
      edit:
        update: Update