Reputation: 27547
Is there a way to test that a model has a specific attribute? Right now I am just using respond_to
like this:
describe Category do
it { should respond_to(:title) }
...
end
to test that the Category model has an attribute, but that only really tests that there is an instance method called title
. However, I can see how in some situations they would behave synonymously.
Upvotes: 9
Views: 11167
Reputation: 544
This is a bit of a necropost, but I wrote a custom rspec matcher that should make testing the presence of a model attribute easier:
RSpec::Matchers.define :have_attribute do |attribute|
chain :with_value do |value|
@value = value
end
match do |model|
r = model.attributes.include? attribute.to_s
r &&= model.attributes[attribute] == @value if @value
r
end
failure_message do |model|
msg = "Expected #{model.inspect} to have attribute #{attribute}"
msg += " with value #{@value}" if @value
msg
end
failure_message_when_negated do |model|
msg = "Expected #{model.inspect} to not have attribute #{attribute}"
msg += " with value #{@value}" if @value
msg
end
end
Upvotes: 1
Reputation: 29419
You can test for the presence of an attribute in an instance of the model with the following:
it "should include the :title attribute" do
expect(subject.attributes).to include(:title)
end
or using the its
method (in a separate gem as of RSpec 3.0):
its(:attributes) { should include("title") }
See the related How do you discover model attributes in Rails. (Nod to @Edmund for correcting the its
example.)
Upvotes: 15
Reputation: 11499
You could test for the class, if that's what you mean:
@category.title.class.should eq String
or you could define a test instance and then test against that.
@category = FactoryGirl.build(:category)
@category.title.should eq <title from factory>
Upvotes: 0