I have a Model method that returns the following when executed.
{"data" => [ {"product" => "PRODUCTA", "orders" => 3, "ordered" => 6, "revenue" => 600.0}, {"product" => "PRODUCTB", "orders" => 1, "ordered" => 5, "revenue" => 100.0}]}
I would like to test to make sure that "revenue" in the first hash is there and then test that the value is equal to 600.
subject { described_class.order_items_by_revenue } it "includes revenue key" do expect(subject).to include(:revenue) end
I am completely lost on how to test this with Rspec.
We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.
Running tests by their file or directory names is the most familiar way to run tests with RSpec. RSpec can take a file name or directory name and run the file or the contents of the directory. So you can do: rspec spec/jobs to run the tests found in the jobs directory.
RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool.
The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument.
RSpec allows you to use the have_key predicate matcher to validate the presence of a key via has_key?
, like so:
subject { described_class.order_items_by_revenue } it "includes revenue key" do expect(subject.first).to have_key(:revenue) end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With