Ruby on Rails + Rspec:包含实例变量的 css 选择器的语法

Ruby on Rails + Rspec: Syntax for css selector containing instance variable

我有一个 rspec 测试,我需要从文章索引页面中专门找到一个 div 块,对应于一个文章 ID,并找到代表 link 的字形destroy/edit 和文章。我在索引页上有一个文章列表,所以我需要特定于 css 选择器。但是,我无法找到解决方案来做到这一点。我尝试了以下方法:

1) 在文章部分给每篇文章添加一个id标签,使用'within'

调出具体的div

文章部分:

<div class = "row" id="<%= article.id %>" >
....more code....
</div>

spec/features/article_spec.rb

describe 'navigate' do

  let!(:user) { FactoryGirl.create(:user) }
  let!(:article)  { FactoryGirl.create(:article) }

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

  describe 'edit' do

    before do
      @article_to_edit = Article.create(title: 'Article to edit', summary: 'Summary of article to edit', description: 'Test to edit this article', user_id: user.id)
    end

    it 'edit and delete icon is visible to article owner from index page' do
      visit articles_path
      within '#{@article_to_edit.id}' do
        expect(page).to have_css('.glyphicon-pencil')
        expect(page).to have_css('.glyphicon-trash')
      end

    end

end

2) 用下面的代码替换 'within' 块以查找文章的特定 href link

expect(page).to have_link('', href: "/articles/#{@article_to_edit.friendly_id}/edit")
expect(page).to have_link('', href: "/articles/#{@article_to_edit.friendly_id}")

Sting 插值仅适用于带双引号的字符串。

只是改变

within '#{@article_to_edit.id}' do

within "#{@article_to_edit.id}" do

在您在问题中发布的代码示例中。并在使用 articles/#{@article_to_edit.friendly_id}...

构建 URL 的地方执行相同操作