- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想测试一个函数如何改变数据库中的某些东西。我正在努力处理与以下 ActiveSupport::TestCase
测试用例等效的 ExUnit:
test "creates a database record" do
post = Post.create title: "See the difference"
assert_difference "Post.published.count" do
post.publish!
end
end
RSpec 版本更优雅,而且由于使用了 lambda,我认为它可以移植到 Elixir/ExUnit。
it "create a database record" do
post = Post.create title: "See the difference"
expect { post.publish! }.to change { Post.count }.by 1
end
有没有比这更优雅(阅读:功能性)的方法:
test "creates a database record", %{conn: conn} do
records_before = count_records
post(conn, "/articles")
records_after = count_records
assert records_before == (records_after - 1)
end
defp count_records do
MyApp.Repo.one((from a in MyApp.Article, select: count("*"))
end
最佳答案
您可以使用宏来获得类似于 Ruby 中的 TestUnit 和 RSpec 示例的东西:
defmacro assert_difference(expr, do: block) do
quote do
before = unquote(expr)
unquote(block)
after_ = unquote(expr)
assert before != after_
end
end
defmacro assert_difference(expr, [with: with], do: block) do
quote do
before = unquote(expr)
unquote(block)
after_ = unquote(expr)
assert unquote(with).(before) == after_
end
end
test "the truth" do
{:ok, agent} = Agent.start_link(fn -> 0 end)
assert_difference Agent.get(agent, &(&1)) do
Agent.update(agent, &(&1 + 1))
end
{:ok, agent} = Agent.start_link(fn -> 0 end)
assert_difference Agent.get(agent, &(&1)), with: &(&1 + 2) do
Agent.update(agent, &(&1 + 2))
end
end
但我不会使用它,除非它被大量使用,否则这只会让除了作者之外的每个人(可能)都更难理解代码。如果您确实使用它,您可能希望将它移动到不同的模块并将其导入到您的测试模块中。
关于testing - 如何为 ExUnit 实现 "assert_difference",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39744696/
context 'with event_type is available create event' do let(:event_type) { EventType.where( name: '
我正在做功能测试,刚刚发现了 assert_difference,如: assert_difference('Account.count') do post :create, :account =
这是一个标准的insert_difference 更新测试: assert_difference 'Article.count' do post :create, article: {...} e
A Book has_many Reviews 和 Review belongs_to Book。我正在使用 rails 4.0 和 ruby 2.0.0p247 我正在运行测试如下: test
我是 Rails 测试的新手,我正在尝试理解对 assert_difference 的调用。来自documentation , 我推断该方法需要一个数值来表示表达式的前一个值和最终值之间的差异。如果我
我想测试一个函数如何改变数据库中的某些东西。我正在努力处理与以下 ActiveSupport::TestCase 测试用例等效的 ExUnit: test "creates a database re
我有以下测试: it 'create action: a user replies to a post for the first time' do login_as user # Actio
我有一个测试,我在其中完成了对拥有一个帐户的用户的付款。该帐户包含余额并有许多交易。 付款完成后,将创建交易并更新帐户余额。 使用 assert_difference 检查交易数量的变化给出了预期的结
这真的是最好的方法吗? assert_difference('u.point', 10) do assert_difference('u.point_logs.count') do ass
Rails 有一个断言,可以在执行块后测试值的差异。来自 here : assert_difference 'Article.count', 1 do post :create, article:
在 Rails 创建的功能测试中(使用脚手架生成模型时),有一个测试如下所示: test "should create product" do assert_difference('Produ
我是一名优秀的程序员,十分优秀!