Testing Datamapper models with RSpec

2019-09-09 12:51发布

I'm testing a Sinatra application, which is using DataMapper, with RSpec.

The following code:

it "should update the item's title" do
  lambda do
    post "/hello/edit", :params => {
      :title => 'goodbye',
      :body  => 'goodbye world'
    }
  end.should change(Snippet, :title).from('hello').to('goodbye')
end

Results in this error:

title should have initially been "hello", but was #<DataMapper::Property::String @model=Snippet @name=:title>

I can of course hack this by removing the lambda and only checking if:

Snippet.first.title.should == 'goodbye' 

But that can't be a long term solution since the .first Snippet may not be the same in the future.

Can someone show me the right syntax?

Thanks.

2条回答
Viruses.
2楼-- · 2019-09-09 12:54

Your spec as written implies that the lambda should actually change the value of the class attribute Snippet.title; I think what you want is something like this:

it "should update the item's title" do
  snippet = Snippet.first(:title => "hello")
  lambda do
    post "/#{snippet.title}/edit", :params => {
      :title => 'goodbye',
      :body  => 'goodbye world'
    }
  end.should change(snippet, :title).from('hello').to('goodbye')
end

Right?

查看更多
相关推荐>>
3楼-- · 2019-09-09 13:14

I finally fixed it using:

it "should update the item's title" do
  snippet = Snippet.first(:title => "hello")
  post "/hello/edit", :params => {
    :title => 'goodbye',
    :body  => 'goodbye world'
  }
  snippet.reload.title.should == 'goodbye'
end

Thanks to @Dan Tao whose answer helped me.

查看更多
登录 后发表回答