How can I state two different values ​​for two different objects with "assert_difference"?

I have the following test below:

it 'create action: a user replies to a post for the first time' do
  login_as user

  # ActionMailer goes up by two because a user who created a topic has an accompanying post.
  # One email for post creation, another for post replies.
  assert_difference(['Post.count', 'ActionMailer::Base.deliveries.size'], 2) do
    post :create, topic_id: topic.id, post: { body: 'Creating a post for the first time.' }
  end
  email = ActionMailer::Base.deliveries

  email.first.to.must_equal [user.email]
  email.subject.must_equal 'Post successfully created'
  must_redirect_to topic_path(topic.id)

  email.last.to.must_equal [user.email]
  email.subject.must_equal 'Post reply sent'
  must_redirect_to topic_path(topic.id)
end

The test above breaks due to a block assert_differencein the code. To pass this test, I need Post.count to increase by 1 and then ActionMailer::Base.deliveries.sizeincrease by 2. This script will pass the test. I tried to rewrite the code in this second type of test.

it 'create action: a user replies to a post for the first time' do
  login_as user

  assert_difference('Post.count', 1) do
    post :create, topic_id: topic.id, post: { body: 'Creating a post for the first time.' }
  end

  # ActionMailer goes up by two because a user who created a topic has an accompanying post.
  # One email for post creation, another for post reply.
  assert_difference('ActionMailer::Base.deliveries.size', 2) do
    post :create, topic_id: topic.id, post: { body: 'Creating a post for the first time.' }
  end

  email = ActionMailer::Base.deliveries

  email.first.to.must_equal [user.email]
  email.subject.must_equal 'Post successfully created'
  must_redirect_to topic_path(topic.id)

  email.last.to.must_equal [user.email]
  email.subject.must_equal 'Post reply sent'
  must_redirect_to topic_path(topic.id)
end

This second iteration is close to what I want, but not quite. The problem with this code is that it creates a post object twice due to create calls in the block assert_difference. I looked at the code assert_differencein the rails api and api docks guides found here ( assert_difference API dock , but that’s not what I need. I need something like this:

assert_difference ['Post.count','ActionMailer::Base.deliveries.size'], 1,2 do
   #create a post
end

Is there any way to implement this?

+4
2

, :

assert_difference("Post.count", 1) do
  assert_difference("ActionMailer::Base.deliveries.size", 2) do
    # Create a post
  end
end
+7

Procs assert_difference, , , .

assert_difference ->{ Post.count } => 1, ->{ ActionMailer::Base.deliveries.size } => 2 do
  # create post
end

0

All Articles