2

I would like to include some dynamic data in my test output.

if I write a test like this then it prints out "it should have '' things"

I figure I'm getting confused with rspec's magic and ruby's blocks as closures.

I can stick at count in a method outside the block but that seems hack-ish.

Any pointers?

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

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


end

if I write a test like the above then it prints out "it should have '' things"

Edit: Another, more specific example

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 '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

在这种情况下,您可以干燥您的测试,并且更容易测试不同的变化。

最好使用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 回答