在erb文件中使用if语句

时间:2014-02-15 04:27:36

标签: ruby-on-rails if-statement erb

我是ruby on rails的新手,正在开发一个示例项目来构建一个论坛。我尝试设置一个可以删除其他管理员的超级管理员。但总是无法通过规范。

这是我的代码 视图/用户/ _user.html.erb

<li>
<%= gravatar_for user, size: 52 %>
<%= link_to user.name, user %>
<% if (current_user.admin? && !current_user?(user) && !user.admin?) ||  current_user.sadmin? %>
| <%= link_to "delete", user, method: :delete,
                data: { confirm: "You sure?" } %>
<% end %>
</li>

规格/请求/ user_page_spec

 describe "delete links" do

  it { should_not have_link('delete') }

  describe "as an admin user" do
    let(:admin) { FactoryGirl.create(:admin) }
    before do
      sign_in admin
      visit users_path
    end

    it { should have_link('delete', href: user_path(User.first)) }
    it "should be able to delete another user" do
      expect do
        click_link('delete', match: :first)
      end.to change(User, :count).by(-1)
    end
    it { should_not have_link('delete', href: user_path(admin)) }
  end

  describe "as an sadmin user" do
    let(:sadmin) { FactoryGirl.create(:sadmin) }
    let(:admin) {FactoryGirl.create(:admin)}
    before do
      sign_in sadmin
      visit users_path
    end

    it { should have_link('delete', href: user_path(User.first)) }
    it "should be able to delete another user" do
      expect do
        click_link('delete', match: :first)
      end.to change(User, :count).by(-1)
    end
    it { should have_link('delete', href: user_path(admin))}
    it { should_not have_link('delete', href: user_path(sadmin)) }
  end
end
end

当我尝试运行规范时,错误是

 1) User pages index delete links as an sadmin user
     Failure/Error: it { should_not have_link('delete', href: user_path(sadmin)) }
       expected #has_link?("delete", {:href=>"/users/422"}) to return false, got true
     # ./spec/requests/user_pages_spec.rb:66:in `block (5 levels) in <top (required)>'

  2) User pages index delete links as an sadmin user
     Failure/Error: it { should have_link('delete', href: user_path(admin))}
       expected #has_link?("delete", {:href=>"/users/423"}) to return true, got false
   # ./spec/requests/user_pages_spec.rb:65:in `block (5 levels) in <top (required)>'

我不确定这是否意味着我在erb文件中使用的语法错误或其他一些我搞砸了?提前致谢

1 个答案:

答案 0 :(得分:0)

    <% if (current_user.admin? && !current_user?(user) && !user.admin?) ||  current_user.sadmin? %>
        | <%= link_to "delete", user, method: :delete,
                data: { confirm: "You sure?" } %>
    <% end %>

,这意味着如果“ current_user.sadmin?”为真,则无论其他条件如何,都会显示该链接。因此,失败是

Failure/Error: it { should_not have_link('delete', href: user_path(sadmin)) }
       expected #has_link?("delete", {:href=>"/users/422"}) to return false, got true

我想

it { should have_link('delete', href: user_path(admin))}

失败,因为管理员用户已被删除

it "should be able to delete another user" do
      expect do
        click_link('delete', match: :first)
      end.to change(User, :count).by(-1)
    end

部分