2

テスト出力に動的データを含めたいと思います。

このようなテストを書くと、「it should have '' things」と出力されます。

rspec のマジックと ruby​​ のブロックをクロージャーとして混同しているようです。

ブロック外のメソッドで count に固執することはできますが、それはハックのようです。

ポインタはありますか?

describe 'things' do
  before :all do
    @count = 3
  end

  it "should have #{@count} things" do
    #....
    page.should have_content("entries: #{@count}")
  end


end

上記のようなテストを書くと、「it should have '' things」と出力されます。

編集:別のより具体的な例

describe 'things' do
  before :all do
    @thing = FactoryGirl.create(:thing)
  end

  it "should display a thing with name #{@thing.name} " do
    #....
    page.should have_css("h1", text: @thing.name)
  end


end
4

2 に答える 2

1

インスタンス変数はitメソッドでは機能しませんが、定数は機能します。describeブロックに従って名前空間を設定するのが好きです。

describe 'things' do
  THINGS_COUNT = 3

  it "should have #{THINGS_COUNT} things" do
    #....
    page.should have_content("entries: #{THINGS_COUNT}")
  end
end

編集:定数を使用すると、値を変更できなくなります。

編集 2 : 動的変数は、より一般的なものにする必要があります。アクティブなレコード オブジェクトを使用する必要はありません。

私が動的変数を使用した一般的なパターンは、入力/出力が異なる同様のテスト用です。

[ 
  [1, true],
  [2, false],
  [3, true]
].each do |number, result|
  it "should return #{result} for #{number}" do
    number.odd?.should == result
  end
 end

この場合、テストを DRY することができ、さまざまなバリエーションをテストしやすくなります。

特定のアクティブなレコード オブジェクトに対してlet(:person) { Factory.create(:person) }またはを使用することをお勧めします。before(:each)

于 2012-06-30T23:46:24.260 に答える
-1
it "should have #{@count} things" do

インスタンス変数を定義する前に評価されるため、 になりますnil

beforeただし、ブロックの外側で変数を定義することはできますが、それは機能します。

describe 'things' do
  count = 3

  it "should have #{count} things" do
    #....
    page.should have_content("entries: #{count}")
  end

end

編集:ブロック内のトップレベルの変数にアクセスできます。

于 2012-06-30T23:44:23.330 に答える