简体   繁体   中英

The site is working perfect but I've got an error when I run “bundle exec rake test”

I've already added my app a support button for microposts and if the user supports the micropost the button changes to "Not Support". Everything is working perfect in localhost but when I run "bundle exec rake test", I have an error.

Error

 $ bundle exec rake test
  1) Error:
   UsersProfileTest#test_profile_display:
   ActionView::Template::Error: undefined method `supports' for nil:NilClass
app/views/shared/_support_form.html.erb:1:in `_app_views_shared__support_form_html_erb__582342844135452036_70190475648520'
app/views/microposts/_micropost.html.erb:21:in `_app_views_microposts__micropost_html_erb___1173022564425897832_70190475500520'
app/views/users/show.html.erb:19:in `_app_views_users_show_html_erb__2940108544736749993_70190457308940'
test/integration/users_profile_test.rb:14:in `block in <class:UsersProfileTest>'

 78 runs, 286 assertions, 0 failures, 1 errors, 0 skips

_support_form.html.erb

<% if support = current_user.supports.find_by_micropost_id(micropost.id) %>
   <% micropost.supports.each do |support| %>
     <% if current_user?(support.user) %>
      <button class="btn" type="submit">
        <%= link_to "Not Support", [support.micropost, support], method: :delete %>
      </button>
    <% end %>
   <% end %>
<% else %>
    <%= form_for ([micropost, @support]) do |f| %>
      <%= render 'shared/error_messages', object: f.object %>
        <%= f.hidden_field :micropost_id %>
        <%= f.hidden_field :user_id %>

    <button class="btn" type="submit">
       Support
    </button>
   <% end %>
<% end %>

_micropost.html.erb

 <%= render 'shared/support_form', micropost: micropost %>

supports_controller.rb

 def create
  @support = Support.new(micropost_id: params[:micropost_id], user: current_user)
  if @support.save
   redirect_to request.referrer || root_url
  else
    redirect_to request.referrer || root_url
  end
 end

 def destroy
    @support.destroy
    redirect_to request.referrer || root_url
 end

You do hot have authenticated user in tests by default, so current_user return nil . Same error may happen in production, if user somehow visits that page without logging-in before.

If you are using devise for auth - see devise wiki on test helper

class SomeControllerTest < ActionController::TestCase
  include Devise::TestHelpers

  def setup
    @request.env["devise.mapping"] = Devise.mappings[:user]
    sign_in FactoryGirl.create(:user) # or other method of making/getting test user
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM