RSpec失败/错误:click_link article.title

时间:2017-09-08 15:21:57

标签: ruby-on-rails rspec

运行rspec测试时我遇到此错误。我试过了click_link" Title 1"并将Article.create分配给变量,但会出现相同的错误。

 Failure/Error: click_link article.title

 Capybara::ElementNotFound:
   Unable to find link "Title 1"

comment_spec.rb

require "rails_helper"

describe 'navigate' do
  let(:user) { FactoryGirl.create(:user) }

  let(:article) do
    Article.create(title: "Title 1", description: "Some description", user_id: user.id)
  end

  before do
    login_as(user, :scope => :user)
  end

  describe 'create' do
    before do
      visit articles_path
    end

    it"permits a signed in user to write a review" do
        click_link article.title
        fill_in "Content", with: "An awesome article"
        click_button "Post"
        expect(page).to have_content("An awesome article")
        expect(current_path).to eq(article_path(article.id))
    end
  end
end

规格/工厂/ user.rb

FactoryGirl.define do
  sequence :email do |n|
    "test#{n}@example.com"
  end

  factory :user do
    name 'Tester'
    email { generate :email }
    password "asdfasdf"
    password_confirmation "asdfasdf"
  end

编辑:

文章/ index.html.erb

      <div class="tab-pane active" id="tab1">
         <% @articles.each do |article| %>
           <%= render 'article', article: article %>
         <% end %>
      </div>

_article.html.erb

<%= link_to article.title, article_path(article) %>

1 个答案:

答案 0 :(得分:0)

let是延迟加载,这意味着在您调用它之前不会对该块进行求值。

    before do
      article # calls the block
      visit articles_path
    end

另一种方法是使用不是延迟加载的let!

require "rails_helper"

describe 'navigate' do
  let(:user) { FactoryGirl.create(:user) }
  let!(:article) do
    Article.create(title: "Title 1", description: "Some description", user_id: user.id)
  end

  before do
    login_as(user, :scope => :user)
  end

  describe 'create' do
    before do
      visit articles_path
    end

    it"permits a signed in user to write a review" do
        click_link article.title
        fill_in "Content", with: "An awesome article"
        click_button "Post"
        expect(page).to have_content("An awesome article")
        expect(current_path).to eq(article_path(article.id))
    end
  end
end