Home>

Creating a portfolio with RoR.
Now I want to add a login feature and test it with rspec.
The reference material is Chapter 8 of the rails tutorial, which is in the form of passing an email and password to the session and logging in based on that information.


  
  <% = form_with (url: login_path, scope:: session, local: true) do | f |%>
    <% = f.label: email%>
    <% = f.email_field: email, class:'form-control'%>
    <% = f.label: password%>
    <% = f.password_field: password, class:'form-control'%>
    <% = f.submit "Log in", class: "btn btn-primary"%>
  <% end%>
  <p>New user?<% = Link_to "Sign up now!", Signup_path%></p>
  

Therefore, regarding the acquisition of parameters

params [: session] [: email]
params [: session] [: password]


And so on

Described as follows in request.spec of rspec

describe'check response' do
  before do
    @user = attributes_for (: user)
    post login_path, params: {session: {email: @ user.email,
                                          password: @ user.password}}
  end
  it'redirect to show' do
    expect (response) .to redirect_to user_path (@user)
  end
  it'return a 302 response' do
    expect (response) .to have_http_status (302)
  end
  it'log in successfully' do
    expect (is_logged_in?). to be_truthy
  end
end
sessions_new GET/sessions/new (.: format) sessions # new
                    login GET/login (.: format) sessions # new
                          POST/login (.: format) sessions # create
                   logout DELETE/logout (.: format) sessions # destroy

The execution result is

NoMethodError:
       undefined method `email'for #<Hash: 0x000055e38deaf620>


Becomes
Please tell me why it is undefined.

  • Answer # 1

    FactoryBot.attributes_for returns a Hash
    FactoryBot.attributes_for (: user) .class # =>Hash

    Hash.new.email # =>NoMethodError: undefined method `email'for {}: Hash

    @user = FactoryBot.build (: user) # or FactoryBot.create (: user)
    post login_path, params: {session: {email: @ user.email, password: @ user.password}}

    Or

    @user = FactoryBot.attributes_for (: user) .slice (: email,: password)
    post login_path, params: {session: @user}


    Try as