1

我不确定如何使 before 块中定义的变量在测试描述中可用。这就是我的意思。

context "name" do
  before do
    @min_size = 1
    @max_size = 255
  end
  context "is valid when it" do
    it "has #{@min_size} character" do
      expect(create(:person, name: Faker::Lorem.characters(@min_size))).to be_valid
    end
    it "has #{@max_size} characters" do
      expect(create(:person, name: Faker::Lorem.characters(@max_size))).to be_valid
    end
    it "has between #{@min_size} and #{@max_size} characters" do
      expect(create(:person, name: Faker::Lorem.characters((@min_size + @max_size)/2))).to be_valid
    end
  end
end

3 个测试通过,但这就是输出的打印方式。注意缺少的最小值和最大值。

name
  is valid when it
    has  character
    has  characters
    has between  and  characters
4

2 回答 2

2

你可以尝试这样的事情:

context "name" do
  min_size = 1
  max_size = 255

  before do
    @min_size = min_size
    @max_size = max_size
  end

  context "is valid when it" do
    it "has #{min_size} character" do
    ...

注意省略“@”登录it

于 2013-09-06T13:39:56.947 回答
1

我不知道它是否比第一个答案更令人困惑,但考虑到在 RSpec 测试中避免使用实例变量的好处(即因为它们评估为nil未定义),您可以使用let而不是beforewhich 允许您在整个示例中使用相同的变量。

context "name" do
  min_size = 1
  max_size = 255

  let(:min_size) {min_size}
  let(:max_size) {max_size}

  context "is valid when it" do
    it "has #{min_size} character" do
    ...
于 2013-09-06T15:46:15.930 回答