Can someone explain to me what is wrong here. Learning RSpec – I am receiving a failed test with message – expected: “Miller” got: nil. I thought that the second ‘before block’ would simply merge the middle_name with the original @valid_attributes. What is the correct way to do this. I know that I can simply say p.middle_name to assign it but I am trying to learn the concepts of RSpec.
describe Person do
describe "Validations" do
subject { p }
before { @valid_attributes={first_name: "Joe", last_name: "Sample"} }
...
context "with optional middle name" do
let(:p) { Person.new(@valid_attributes) }
before { @valid_attributes.merge({middle_name: "Miller"}) }
its(:middle_name) { should eq("Miller") }
end
end
end
Your problem:
Hash#mergereturns a new hash, you wantHash#update.How to do it better? This is not just an advice for testing, but for programming in general: if you update and reuse variables you’re gonna hit some problems with state; take a more functional approach. In this particular case you should use factory_girl or similar gem to easily create objects without having a
@valid_attributesbeing updated who knows where.