繁体   English   中英

该网站运行正常,但是当我运行“ bundle exec rake test”时出现错误

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

我已经为我的应用程序添加了微博支持按钮,如果用户支持微博,则该按钮将变为“不支持”。 一切都在localhost上运行良好,但是当我运行“ bundle exec rake test”时,出现错误。

错误

 $ 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

默认情况下,您确实在测试中拥有经过身份验证的用户,所以current_user返回nil 如果用户不经登录就以某种方式访问​​该页面,则在生产中可能会发生相同的错误。

如果您使用devise进行身份验证-请参阅测试助手上的devise Wiki

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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