Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec tests: it { should respond_to() }

If you have a list of attributes that you are testing for their presence and you have the following:

before do
  @attr = Employee.new(name: "One",
                       email: "[email protected]")
end

subject { @attr }

it { should respond_to(:name) }
it { should respond_to(:email) }

it { should be_valid }

Can you then test for the reverse, namely if these attributes are blank using:

it { should_not respond_to(:reverse, :blank) }
it { should_not be_valid }

I did try the above, but I do not understand the issues all that well, even after reading this discussion.

Does anyone know how to use the same initialization to test for presence and then to turn around and test for blank attributes?

like image 689
thomasvermaak Avatar asked Dec 06 '25 08:12

thomasvermaak


1 Answers

I think you've misunderstood what respond_to does in your tests. When you do

it { should respond_to(:name) }

You're asserting that @attr.respond_to(:name) returns true, meaning that the method is present, not that it's returning a value. If you want to test that there's a value being returned, you could do something like:

its(:name){ should be_present }

That will make sure that the result of calling the name method returns a non-false, non-empty value. Then, when you reverse that test

its(:name){ should_not be_present }

You're asserting that the name method is returning blank. You'll have to create a different setup for the second test, since you're testing an object in a different state.

like image 120
Emily Avatar answered Dec 08 '25 23:12

Emily