katjass
katjass

Reputation: 319

Capybara::ElementNotFound: Unable to find visible link

I'm having trouble with my test for a method which lets an admin user promote other users to admin by the click of "Promote to Admin". It lies in my controller, I'm writing a feature test for it. I'm using Rails 5.1.4.

  def promote
   @user = User.find(params[:user_id])
   if @user.toggle!(:admin)
    flash[:success] = "User is promoted to admin."
    redirect_to root_path
   else
    flash[:notice] = "Can't promote."
    redirect_to root_path
   end
  end

This is the test:

describe "Promotion" do
 before do
  login_as(User.create!(name: "lala", email: Faker::Internet.email, 
  password: "lalala", admin: true))
  visit users_path
 end

context "to admin" do
 it "promotes user to admin" do
  click_link("Promote to Admin", :match => :first)
  expect(current_path).to eq user_promote_path
 end
end
end

It gives me the error: Capybara::ElementNotFound: Unable to find visible link "Promote to Admin" which I think is because I'm not accessing the right page, trying to log in as admin is perhaps not working. Any suggestion would be very appreciated!

Upvotes: 2

Views: 2339

Answers (2)

Thomas Walpole
Thomas Walpole

Reputation: 49890

The most likely reason for your test failing is that you don't appear to have created any other users beyond the one you're logging in as. If you haven't then there wouldn't be any users to show "Promote to Admin" links for. You can always save the page or just do puts page.html to make sure what you think is on the page actually is.

A second issue with your test is that you should never use the eq matcher with current_path. You should be using the Capybara provided path matcher of you want stable tests

expect(page).to have_current_path(user_promote_path)

Upvotes: 0

Samy Kacimi
Samy Kacimi

Reputation: 1238

If you want to be sure that you're on the right page, you can do some debugging with:

  • save_and_open_page (opens your browser)
  • save_and_open_screenshot (takes a screenshot and opens it)

If it's all good, maybe Capybara can't find the link : Is it a screen size/responsive issue ? If yes, you can configure the window size that Capybara uses (see this link)

If the test still does not pass, maybe the link is not visible by default ? You can add to option visible: false in click_link to precise that.

Upvotes: 0

Related Questions