1

I'm not sure how to make variables defined in the before block be available in the test description. Here is what I mean.

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

The 3 tests pass, but this is how the output prints. Notice the missing min and max values.

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未定義の場合に評価されるため)を考えると、 whichletの代わりに使用beforeできます。例全体で同じ変数を使用してください。

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 に答える