# 提取 RSpec 'let'

> For the complete documentation index, see [llms.txt](https://www.jetbrains.com/zh-cn/help/ruby/llms.txt).

> **TL;DR**
> `重构 | 提取/引入 | RSpec 'let'`
>
>
>
> `⌘ ⇧ L` (Windows), `⌘ ⇧ L` (macOS), `⌘ ⇧ L` (IntelliJ IDEA Classic (macOS)), `⌘ ⌃ ⌥ L` (macOS System Shortcuts), `⌘ ⇧ L` (XWin), `⌘ ⇧ L` (GNOME), `⌘ ⇧ L` (KDE), `⌘ ⇧ L` (Emacs), `⌘ ⇧ L` (Sublime Text), `⌘ ⇧ L` (Sublime Text (macOS)), `⌘ ⇧ L` (Visual Studio), `⌘ ⇧ L` (Visual Studio (macOS)), `⌘ ⇧ L` (TextMate), `⌘ ⇧ L` (NetBeans), `⌘ ⇧ L` (Eclipse), `⌘ ⇧ L` (Eclipse (macOS))

提取 RSpec 'let'  重构允许您将指定的代码片段提取到一个带有记忆功能的辅助方法中。 为此，请执行以下步骤：

Procedure:

1. 在 spec 文件中，选择所需的代码段，然后从主菜单中选择  `重构 | 重构此项 | RSpec 'let'`  ( `⌘ ⇧ L` (Windows), `⌘ ⇧ L` (macOS), `⌘ ⇧ L` (IntelliJ IDEA Classic (macOS)), `⌘ ⌃ ⌥ L` (macOS System Shortcuts), `⌘ ⇧ L` (XWin), `⌘ ⇧ L` (GNOME), `⌘ ⇧ L` (KDE), `⌘ ⇧ L` (Emacs), `⌘ ⇧ L` (Sublime Text), `⌘ ⇧ L` (Sublime Text (macOS)), `⌘ ⇧ L` (Visual Studio), `⌘ ⇧ L` (Visual Studio (macOS)), `⌘ ⇧ L` (TextMate), `⌘ ⇧ L` (NetBeans), `⌘ ⇧ L` (Eclipse), `⌘ ⇧ L` (Eclipse (macOS)))。

![提取方法](https://resources.jetbrains.com/help/img/idea/2026.3/rm_refactoring_extract_rspec_let.png)

2. 指定辅助方法的所需名称，然后按 `Enter` (Windows), `⏎` (macOS), `⏎` (IntelliJ IDEA Classic (macOS)), `⏎` (macOS System Shortcuts), `Enter` (XWin), `Enter` (GNOME), `Enter` (KDE), `Enter` (Emacs), `Enter` (Sublime Text), `⏎` (Sublime Text (macOS)), `Enter` (Visual Studio), `⏎` (Visual Studio (macOS)), `Enter` (TextMate), `Enter` (NetBeans), `Enter` (Eclipse), `⏎` (Eclipse (macOS))。

![提取方法](https://resources.jetbrains.com/help/img/idea/2026.3/rm_refactoring_extract_rspec_let_name.png)

3. 如果找到多个代码片段的出现，RubyMine 将建议用辅助方法调用替换这些出现。

![提取方法](https://resources.jetbrains.com/help/img/idea/2026.3/rm_refactoring_extract_rspec_let_replace.png)

单击   是   以替换找到的出现。 如果您只想替换选定的出现，请单击   否  。

> **Note:**
> 如果您单击   是  ，RubyMine 将建议逐一或一次性替换找到的出现。

## 示例

Before:

```RUBY
describe "GetTime" do
    it "gets the same time" do
        puts Time.now
        sleep(3)
        puts Time.now
    end
end

```

After:

```RUBY
describe "GetTime" do
    let(:current_time) { Time.now }

    it "gets the same time" do
        puts current_time
        sleep(3)
        puts current_time
    end
end

```

