0

For this test:

describe "can translate" do
  let(:from){592}
  it @from do
    expect(Translator.three_digits(from)).to eq 'five hundred ninety two'
  end
end 

I need to refer to from as @from when using it in the it statement but as just from when using it in the expect test. In each case trying to use the other format raises errors as unknown. Why the difference?
Does it reflect something I'm not doing/understanding correctly?

After more digging I realized the @ instance variable isn't working correctly - it just isn't reporting an error because an @variable can be empty. However if the tests fails and the test text descriptions is output the value for that variable is blank.

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497

2 Answers2

0

Try expect{} instead of expect():

describe "can translate" do
  let(:from){592}
  it "some description here what I expect it to do" do
    expect{Translator.three_digits(from)}.to eq 'five hundred ninety two'
  end
end

or omit its description and do in one line:

it { expect{Translator.three_digits(from) }.to eq 'five hundred ninety two' }
pawel7318
  • 3,383
  • 2
  • 28
  • 44
0

Are you expecting the let(:from) { 592 } declaration to also initialize a @from instance variable? If so, I don't think it does. If not, could you please expand upon why you need to refer to from as @from in your it block? As far as I understand your question, the reason why your @from instance variable isn't working the way you expect it to is because it's nil because you haven't declared a @from anywhere in the spec. Here's a small test:

describe 'foo' do
  let(:foo) { 1 }
  it "@foo's value is #{@foo.inspect}" do
    expect(foo).to eq(2) # deliberate fail
  end
end

The result:

1) foo @foo's value is nil # no @foo here
   Failure/Error: expect(foo).to eq(2)

     expected: 2
          got: 1

   (compared using ==)

As an aside, I think the potential for confusion when using instance variables in specs is exemplified in the following spec:

describe 'foo' do
  let(:foo) { 1 }
  before { @foo = 2 }
  @foo = 3
  it "@foo's value is #{@foo.inspect}" do
    expect(@foo).to eq(2) # this test passes cause it uses @foo in before block 
    expect(foo).to eq(2) # deliberate fail
  end
end

The result:

1) foo @foo's value is 3 # it block uses @foo in describe block 
   Failure/Error: expect(foo).to eq(2)

     expected: 2
          got: 1

   (compared using ==)
Paul Fioravanti
  • 16,423
  • 7
  • 71
  • 122