ruby-on-rails - 如何与 rspec 中的许多 "it"示例共享变量

标签 ruby-on-rails rspec factory-bot

我正在使用 let 来使用 Factory Girl 创建用户记录。不过,我想在上下文中的 2 个测试中使用完全相同的变量,因为 user_id 和电子邮件对于我发送的外部 API 很重要。

但是,我没有运气制作一个变量来在示例中使用。这是我当前的代码

context "User" do
    let(:user) { FactoryGirl.create(:user) }

    it "should create user and return 'nil'" do
      expect(send_preferences(user, "new")).to eq nil
    end

    it "should not create user preferences again after sending two consecutive same requests" do
      expect(send_preferences(user, "new")).to eq "User preferences already saved. No need to re-save them."
    end

    it "should update user preferences" do
      expect(send_preferences(user, "update")).to eq nil
    end
  end

有什么线索吗?

最佳答案

您可以在let内使用let:

context "User" do
  let(:email_address) { '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="106475636450647563643e737f7d" rel="noreferrer noopener nofollow">[email protected]</a>' }
  let(:user) { FactoryGirl.create(:user, email_address: email_address) }

然后,您还可以在所有测试中访问 email_address 变量。

这是可行的,因为以前每次创建用户时,工厂都会随机生成电子邮件地址,因为我们没有在任何地方为其设置值。因此,我们在每个测试中调用以下代码:

send_preferences(user, "new")

它称为“user”let,它创建了一个具有完全随机电子邮件地址的新用户(因为我们没有为其提供特定的电子邮件值)。因此,在后端 API 调用期间,它每次都会发送不同的电子邮件地址。

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

但是,当我们将电子邮件地址“let”定义为“[email protected]”时',并将其传递到用户工厂,如我提供的代码中所示,我们用自己的静态值覆盖随机生成的电子邮件地址,因此,每次我们再次调用代码时:

send_preferences(user, "new") 

它现在触发用户工厂创建,它也采用我们新的“email_address”let,它始终设置为特定值 [email protected]每次被调用时。

let(:email_address) { '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="493d2c3a3d093d2c3a3d672a2624" rel="noreferrer noopener nofollow">[email protected]</a>' }
let(:user) { FactoryGirl.create(:user, email_address: email_address) }

因此,当进行后端 API 调用时,电子邮件地址始终是我们设置的地址。

此外,由于它是一个 let,如果我们愿意,我们可以在任何测试本身中使用该变量。例如:

it 'should set the email address' do
  expect(user.email_address).to eq(email_address)
end

很难用几句话解释清楚,但如果仍然不清楚,请告诉我。

关于ruby-on-rails - 如何与 rspec 中的许多 "it"示例共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41695479/

相关文章:

ruby-on-rails - 使用范围过滤整数字段

ruby-on-rails - 工厂女孩和回形针附件

ruby-on-rails - 如何测试渲染 :file => 'public/404.html' in Rspec 2?

ruby-on-rails - 工厂女郎 : Populate a has many relation preserving build strategy

ruby-on-rails - 使用 FactoryGirl 进行 Controller 测试

ruby-on-rails - RoR 中的关系表

ruby-on-rails - 如何在 Rails 模型中包含 gem 的类方法?

ruby-on-rails - 如何使用 rspec 为序列化器编写单元测试

ruby-on-rails - 当 guard 退出时, Spring 并没有停止

ruby-on-rails - 我们应该在 Rails Factories 中使用 Faker 吗?